Java 类com.google.common.reflect.ClassPath.ClassInfo 实例源码

项目:living-documentation    文件:PlantumlClassDiagramBuilder.java   
public String generate() throws MojoExecutionException {
    final ClassPath classPath = initClassPath();
    final Set<ClassInfo> allClasses = classPath.getTopLevelClassesRecursive(prefix);

    String diagram = classDiagramBuilder
            .addClasse(allClasses.stream()
                    // apply filters
                    .filter(defaultFilter())
                    .filter(additionalClassPredicate)
                    .map(ClassInfo::load).collect(Collectors.toList()))
            .excludes(excludes)
            .setHeader(readHeader())
            .setFooter(readFooter())
            .withNamesMapper(namesMapper)
            .withLinkMaker(this)
            .withDependencies(diagramWithDependencies)
            .build();
    return diagram;
}
项目:guava-mock    文件:ClassPathTest.java   
public void testGetSimpleName() {
  ClassLoader classLoader = getClass().getClassLoader();
  assertEquals("Foo",
      new ClassInfo("Foo.class", classLoader).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Foo.class", classLoader).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Bar$Foo.class", classLoader).getSimpleName());
  assertEquals("",
      new ClassInfo("a/b/Bar$1.class", classLoader).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Bar$Foo.class", classLoader).getSimpleName());
  assertEquals("",
      new ClassInfo("a/b/Bar$1.class", classLoader).getSimpleName());
  assertEquals("Local",
      new ClassInfo("a/b/Bar$1Local.class", classLoader).getSimpleName());
}
项目:googles-monorepo-demo    文件:ClassPathTest.java   
public void testGetSimpleName() {
  ClassLoader classLoader = getClass().getClassLoader();
  assertEquals("Foo",
      new ClassInfo("Foo.class", classLoader).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Foo.class", classLoader).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Bar$Foo.class", classLoader).getSimpleName());
  assertEquals("",
      new ClassInfo("a/b/Bar$1.class", classLoader).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Bar$Foo.class", classLoader).getSimpleName());
  assertEquals("",
      new ClassInfo("a/b/Bar$1.class", classLoader).getSimpleName());
  assertEquals("Local",
      new ClassInfo("a/b/Bar$1Local.class", classLoader).getSimpleName());
}
项目:wizards-of-lua    文件:WolTestEnvironment.java   
@SuppressWarnings("unchecked")
private Iterable<Class<? extends AbstractMessage>> findMessageClasses() {
  try {
    List<Class<? extends AbstractMessage>> result = new ArrayList<>();
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    ClassPath classpath = ClassPath.from(classloader);
    ImmutableSet<ClassInfo> xx =
        classpath.getTopLevelClassesRecursive("net.wizardsoflua.testenv.net");
    Iterable<ClassInfo> yy = Iterables.filter(xx, input -> {
      Class<?> cls = input.load();
      return AbstractMessage.class.isAssignableFrom(cls)
          && !Modifier.isAbstract(cls.getModifiers());
    });
    for (ClassInfo classInfo : yy) {
      result.add((Class<? extends AbstractMessage>) classInfo.load());
    }
    return result;
  } catch (IOException e) {
    throw new UndeclaredThrowableException(e);
  }
}
项目:AuxiliumLib    文件:ClassUtil.java   
@API public static List<Class<?>> getClasses(String path)
{
    try
    {
        ClassPath classPath = ClassPath.from(ClassUtil.class.getClassLoader());
        Set<ClassInfo> classInfo = classPath.getTopLevelClassesRecursive(path);
        Iterator<ClassInfo> iterator = classInfo.iterator();

        List<Class<?>> classes = new ArrayList<>();
        while(iterator.hasNext())
        {
            ClassInfo ci = iterator.next();
            Optional<Class<?>> classOptional = getClass(ci.getName());
            classOptional.ifPresent(classes::add);
        }

        return classes;
    }
    catch(IOException e)
    {
        throw new UncheckedIOException(e);
    }
}
项目:checkstyle-backport-jre6    文件:CheckUtil.java   
/**
 * Gets checkstyle's modules in the given package recursively.
 * @param packageName the package name to use
 * @param loader the class loader used to load Checkstyle package name
 * @return the set of checkstyle's module classes
 * @throws IOException if the attempt to read class path resources failed
 * @see ModuleReflectionUtils#isCheckstyleModule(Class)
 */
private static Set<Class<?>> getCheckstyleModulesRecursive(
        String packageName, ClassLoader loader) throws IOException {
    final ClassPath classPath = ClassPath.from(loader);
    final Set<Class<?>> result = new HashSet<Class<?>>();
    for (ClassInfo clsInfo : classPath.getTopLevelClassesRecursive(packageName)) {
        final Class<?> cls = clsInfo.load();

        if (ModuleReflectionUtils.isCheckstyleModule(cls)
                && !cls.getName().endsWith("Stub")
                && !cls.getCanonicalName()
                .startsWith("com.puppycrawl.tools.checkstyle.internal.testmodules")
                && !cls.getCanonicalName()
                .startsWith("com.puppycrawl.tools.checkstyle.packageobjectfactory")) {
            result.add(cls);
        }
    }
    return result;
}
项目:Alchemy    文件:AlchemyTransformerManager.java   
@Unsafe(Unsafe.ASM_API)
private static void loadAllProvider() throws Exception {
    ClassPath path = ClassPath.from(AlchemyTransformerManager.class.getClassLoader());
    for (ClassInfo info : path.getAllClasses())
        if (info.getName().startsWith(MOD_PACKAGE)) {
            ClassReader reader = new ClassReader(info.url().openStream());
            ClassNode node = new ClassNode(ASM5);
            reader.accept(node, 0);
            if (checkSideOnly(node)) {
                loadPatch(node);
                loadField(node);
                loadProxy(node);
                loadHook(node);
                loadTransform(node, info);
            }
        }
}
项目:nomulus    文件:RegistryToolTest.java   
/**
 * Gets the set of all non-abstract classes implementing the {@link Command} interface (abstract
 * class and interface subtypes of Command aren't expected to have cli commands). Note that this
 * also filters out HelpCommand, which has special handling in {@link RegistryCli} and isn't in
 * the command map.
 *
 * @throws IOException if reading the classpath resources fails.
 */
@SuppressWarnings("unchecked")
private ImmutableSet<Class<? extends Command>> getAllCommandClasses() throws IOException {
  ImmutableSet.Builder<Class<? extends Command>> builder = new ImmutableSet.Builder<>();
  for (ClassInfo classInfo : ClassPath
      .from(getClass().getClassLoader())
      .getTopLevelClassesRecursive(getPackageName(getClass()))) {
    Class<?> clazz = classInfo.load();
    if (Command.class.isAssignableFrom(clazz)
        && !Modifier.isAbstract(clazz.getModifiers())
        && !Modifier.isInterface(clazz.getModifiers())
        && !clazz.equals(HelpCommand.class)) {
      builder.add((Class<? extends Command>) clazz);
    }
  }
  return builder.build();
}
项目:livingdocumentation-workshop    文件:SystemDiagramTest.java   
protected void printActor(Digraph digraph, ClassInfo ci, JavaProjectBuilder builder) {
    // final String options =
    // "shape=box, style=invis, shapefile=\"Turing.png\"";
    final String url = ", URL=\"" + (SCM_BASE_URL + "/" + SOURCE_TREE + "/") + toPath(ci) + "\"";
    final String options = "shape=box, style=filled,fillcolor=\"#C0D0C0\"" + url;

    final ExternalActor[] actors = ci.load().getAnnotationsByType(ExternalActor.class);
    for (ExternalActor actor : actors) {
        digraph.addNode(ci.getName()).setLabel(wrap(actor.name(), 19)).setComment(ci.getSimpleName())
                .setOptions(options); // .addStereotype(actorType(actor.type()))

        final String label = getComment(ci, builder);
        switch (actor.direction()) {
        case API:
            digraph.addAssociation(ci.getName(), "system").setLabel(label).setOptions(NOTE_EDGE_STYLE);
            break;
        case SPI:
            digraph.addAssociation("system", ci.getName()).setLabel(label).setOptions(NOTE_EDGE_STYLE);
            break;
        default:
            digraph.addAssociation("system", ci.getName()).setLabel(label).setOptions(NOTE_EDGE_STYLE);
            digraph.addAssociation(ci.getName(), "system").setLabel(label).setOptions(NOTE_EDGE_STYLE);
        }
    }
}
项目:guava-libraries    文件:ClassPathTest.java   
public void testGetTopLevelClasses() throws Exception {
  Set<String> names = Sets.newHashSet();
  Set<String> strings = Sets.newHashSet();
  Set<Class<?>> classes = Sets.newHashSet();
  Set<String> packageNames = Sets.newHashSet();
  Set<String> simpleNames = Sets.newHashSet();
  ClassPath classpath = ClassPath.from(getClass().getClassLoader());
  for (ClassInfo classInfo
      : classpath.getTopLevelClasses(ClassPathTest.class.getPackage().getName())) {
    names.add(classInfo.getName());
    strings.add(classInfo.toString());
    classes.add(classInfo.load());
    packageNames.add(classInfo.getPackageName());
    simpleNames.add(classInfo.getSimpleName());
  }
  assertThat(names).containsAllOf(ClassPath.class.getName(), ClassPathTest.class.getName());
  assertThat(strings).containsAllOf(ClassPath.class.getName(), ClassPathTest.class.getName());
  assertThat(classes).containsAllOf(ClassPath.class, ClassPathTest.class);
  assertThat(packageNames).contains(ClassPath.class.getPackage().getName());
  assertThat(simpleNames).containsAllOf("ClassPath", "ClassPathTest");
  assertFalse(classes.contains(ClassInSubPackage.class));
}
项目:guava-libraries    文件:ClassPathTest.java   
public void testGetSimpleName() {
  assertEquals("Foo",
      new ClassInfo("Foo.class", getClass().getClassLoader()).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Foo.class", getClass().getClassLoader()).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Bar$Foo.class", getClass().getClassLoader()).getSimpleName());
  assertEquals("",
      new ClassInfo("a/b/Bar$1.class", getClass().getClassLoader()).getSimpleName());
  assertEquals("Foo",
      new ClassInfo("a/b/Bar$Foo.class", getClass().getClassLoader()).getSimpleName());
  assertEquals("",
      new ClassInfo("a/b/Bar$1.class", getClass().getClassLoader()).getSimpleName());
  assertEquals("Local",
      new ClassInfo("a/b/Bar$1Local.class", getClass().getClassLoader()).getSimpleName());

}
项目:digg    文件:SerializableClassesTest.java   
@Test
public void serializableClassesMustDefineSerialVersionUID() throws IOException {

    List<Class<?>> serializableClassesWithoutSerialVersionUID = ClassPath
        .from(SerializableClassesTest.class.getClassLoader())
        .getTopLevelClassesRecursive("no.digipost")
        .stream().map(ClassInfo::load)
        .flatMap(c -> Stream.concat(Stream.of(c), Stream.of(c.getDeclaredClasses())))
        .filter(c -> !c.getName().contains("Test"))
        .filter(c -> !Enum.class.isAssignableFrom(c))
        .filter(Serializable.class::isAssignableFrom)
        .filter(c -> {
            try {
                c.getDeclaredField("serialVersionUID");
                return false;
            } catch (NoSuchFieldException e) {
                return true;
            }
        }).collect(toList());

    assertThat(serializableClassesWithoutSerialVersionUID, empty());
}
项目:tensorics-core    文件:ClasspathConstantScanner.java   
private Set<ClassInfo> allClasses() {
    ClassPath cpScanner;
    try {
        cpScanner = ClassPath.from(ClasspathConstantScanner.class.getClassLoader());
    } catch (IOException e) {
        LOGGER.warn("Cannot scan classes. No Constants will be returned.");
        return Collections.emptySet();
    }
    return cpScanner.getTopLevelClasses().stream().filter(ci -> {
        if (basePackages.isEmpty()) {
            return true;
        } else {
            return basePackages.stream().anyMatch(p -> ci.getPackageName().startsWith(p));
        }
    }).collect(Collectors.toSet());
}
项目:diqube    文件:DiqubeThriftServiceInfoManager.java   
@PostConstruct
public void initialize() {
  annotationByServiceInterface = new HashMap<>();

  ImmutableSet<ClassInfo> classInfos;
  try {
    classInfos =
        ClassPath.from(DiqubeThriftServiceInfoManager.class.getClassLoader()).getTopLevelClassesRecursive(BASE_PKG);
  } catch (IOException e) {
    throw new RuntimeException("Could not parse ClassPath.");
  }

  for (ClassInfo classInfo : classInfos) {
    Class<?> clazz = classInfo.load();

    DiqubeThriftService annotation = clazz.getAnnotation(DiqubeThriftService.class);
    if (annotation != null)
      annotationByServiceInterface.put(annotation.serviceInterface(), new DiqubeThriftServiceInfo<>(annotation));
  }
  logger.info("Found {} diqube services in {} scanned classes.", annotationByServiceInterface.size(),
      classInfos.size());
}
项目:diqube    文件:Tool.java   
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException {
  Collection<ClassInfo> classInfos =
      ClassPath.from(Tool.class.getClassLoader()).getTopLevelClassesRecursive(BASE_PKG);

  Map<String, ToolFunction> toolFunctions = new HashMap<>();

  for (ClassInfo classInfo : classInfos) {
    Class<?> clazz = classInfo.load();
    ToolFunctionName toolFunctionName = clazz.getAnnotation(ToolFunctionName.class);
    if (toolFunctionName != null) {
      ToolFunction functionInstance = (ToolFunction) clazz.newInstance();
      toolFunctions.put(toolFunctionName.value(), functionInstance);
    }
  }

  new Tool(toolFunctions).execute(args);
}
项目:diqube    文件:IdentityToolFunction.java   
private Map<String, Pair<AbstractActualIdentityToolFunction, IsActualIdentityToolFunction>> loadActualFunctions() {
  try {
    Collection<ClassInfo> classInfos =
        ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive(BASE_PKG);

    Map<String, Pair<AbstractActualIdentityToolFunction, IsActualIdentityToolFunction>> toolFunctions =
        new HashMap<>();

    for (ClassInfo classInfo : classInfos) {
      Class<?> clazz = classInfo.load();
      IsActualIdentityToolFunction isActualIdentityToolFunctionAnnotation =
          clazz.getAnnotation(IsActualIdentityToolFunction.class);
      if (isActualIdentityToolFunctionAnnotation != null) {
        AbstractActualIdentityToolFunction functionInstance =
            (AbstractActualIdentityToolFunction) clazz.newInstance();

        toolFunctions.put(isActualIdentityToolFunctionAnnotation.identityFunctionName(),
            new Pair<>(functionInstance, isActualIdentityToolFunctionAnnotation));
      }
    }

    return toolFunctions;
  } catch (IOException | InstantiationException | IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}
项目:closure-templates    文件:CopyPolicyTest.java   
@Test
public void testCopy() throws IOException {
  // We use top level classes to ignore node types defined as inner classes for tests.
  ImmutableSet<ClassInfo> topLevelClasses =
      ClassPath.from(ClassLoader.getSystemClassLoader()).getTopLevelClasses();
  Set<String> errors = new LinkedHashSet<>();
  for (ClassInfo clazz : topLevelClasses) {
    if (clazz.getPackageName().startsWith("com.google.template.soy")) {
      Class<?> cls = clazz.load();
      if (Node.class.isAssignableFrom(cls)) {
        if (cls.isInterface()) {
          continue;
        }
        if (Modifier.isAbstract(cls.getModifiers())) {
          checkAbstractNode(cls, errors);
        } else {
          checkConcreteNode(cls, errors);
        }
      }
    }
  }
  if (!errors.isEmpty()) {
    fail("Copy policy failure:\n" + Joiner.on('\n').join(errors));
  }
}
项目:bazel    文件:Classpath.java   
/** Finds all classes that live in or below the given package. */
public static Set<Class<?>> findClasses(String packageName) throws ClassPathException {
  Set<Class<?>> result = new LinkedHashSet<>();
  String packagePrefix = (packageName + '.').replace('/', '.');
  try {
    for (ClassInfo ci : ClassPath.from(Classpath.class.getClassLoader()).getAllClasses()) {
      if (ci.getName().startsWith(packagePrefix)) {
        try {
          result.add(ci.load());
        } catch (UnsatisfiedLinkError | NoClassDefFoundError unused) {
          // Ignore: we're most likely running on a different platform.
        }
      }
    }
  } catch (IOException e) {
    throw new ClassPathException(e.getMessage());
  }
  return result;
}
项目:docker-java    文件:ModelsSerializableTest.java   
@Test
public void allModelsSerializable() throws IOException, NoSuchFieldException, IllegalAccessException {
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    for (ClassInfo classInfo : from(contextClassLoader).getTopLevelClasses("com.github.dockerjava.api.model")) {
        if (classInfo.getName().endsWith("Test")) {
            continue;
        }

        final Class<?> aClass = classInfo.load();
        if (aClass.getProtectionDomain().getCodeSource().getLocation().getPath().endsWith("test-classes/")
                || aClass.isEnum()) {
            continue;
        }

        LOG.debug("aClass: {}", aClass);
        assertThat(aClass, typeCompatibleWith(Serializable.class));

        final Object serialVersionUID = FieldUtils.readDeclaredStaticField(aClass, "serialVersionUID", true);
        if (!excludeClasses.contains(aClass.getName())) {
            assertThat(serialVersionUID, instanceOf(Long.class));
            assertThat("Follow devel docs", (Long) serialVersionUID, is(1L));
        }
    }
}
项目:inflection    文件:AssociationRegistry.java   
public void scan( ClassLoader loader, String[] includeFilters, String[] excludeFilters )
{
    if ( performedScan )
        throw new RuntimeException( String.format( "Scan for this %s was already performed.", AssociationRegistry.class.getSimpleName() ) );

    Set< String > adjustedIncludeFilters = Arrays.asList( includeFilters ).stream().map( includeFilter -> includeFilter.replace( "*", ".*" ) ).collect( Collectors.toSet() );
    Set< String > adjustedExcludeFilters = Arrays.asList( excludeFilters ).stream().map( excludeFilter -> excludeFilter.replace( "*", ".*" ) ).collect( Collectors.toSet() );

    Set< ClassInfo > allClasses = ExceptionWrapper.ClassPath_from( loader ).getAllClasses();
    Set< ClassInfo > classesAfterInclusion = allClasses.stream().filter( classInfo -> classInfoMatchesFilter( classInfo, adjustedIncludeFilters ) ).collect( Collectors.toSet() );
    Set< ClassInfo > classesAfterExclusion = classesAfterInclusion.stream().filter( classInfo -> !classInfoMatchesFilter( classInfo, adjustedExcludeFilters ) ).collect( Collectors.toSet() );

    Pass1Scanner pass1Scanner = new Pass1Scanner( classesAfterExclusion, registeredClasses );
    Pass2Scanner pass2Scanner = new Pass2Scanner( registeredClasses );
    Pass3Scanner pass3Scanner = new Pass3Scanner( registeredClasses );
    pass1Scanner.scan();
    pass2Scanner.scan();
    pass3Scanner.scan();

    performedScan = true;
}
项目:inflection    文件:CompilationJob.java   
Set< Class< ? > > getAllClassesInClassPath2()
{
    if ( allClassesInClassPath2 == null )
    {
        allClassesInClassPath2 = new HashSet< Class< ? > >();
        Set< ClassInfo > allClassInfos = getAllClassesInClassPath();

        for ( ClassInfo classInfo : allClassInfos )
        {
            try
            {
                allClassesInClassPath2.add( classInfo.load() );
            }
            catch ( LinkageError e )
            {
            }
        }
    }

    return allClassesInClassPath2;
}
项目:grpc-java    文件:ChannelAndServerBuilderTest.java   
/**
 * Javadoc.
 */
@Parameters(name = "class={0}")
public static Collection<Object[]> params() throws Exception {
  ClassLoader loader = ChannelAndServerBuilderTest.class.getClassLoader();
  List<Object[]> classes = new ArrayList<Object[]>();
  for (ClassInfo classInfo : ClassPath.from(loader).getTopLevelClassesRecursive("io.grpc")) {
    Class<?> clazz = Class.forName(classInfo.getName(), false /*initialize*/, loader);
    if (ServerBuilder.class.isAssignableFrom(clazz) && clazz != ServerBuilder.class) {
      classes.add(new Object[]{clazz});
    } else if (ManagedChannelBuilder.class.isAssignableFrom(clazz)
        && clazz != ManagedChannelBuilder.class ) {
      classes.add(new Object[]{clazz});
    }
  }
  Truth.assertWithMessage("Unable to find any builder classes").that(classes).isNotEmpty();
  return classes;
}
项目:assertj-assertions-generator    文件:ClassUtil.java   
private static Set<TypeToken<?>> getPackageClassesFromClasspathJars(String packageName, ClassLoader classLoader)
    throws IOException {
  ImmutableSet<ClassInfo> classesInfo = ClassPath.from(classLoader).getTopLevelClassesRecursive(packageName);
  Set<TypeToken<?>> classesInPackage = new HashSet<>();
  for (ClassInfo classInfo : classesInfo) {
    classesInPackage.add(TypeToken.of(classInfo.load()));
  }

  Set<TypeToken<?>> filteredClassesInPackage = new HashSet<>();
  for (TypeToken<?> classFromJar : classesInPackage) {
    if (isClassCandidateToAssertionsGeneration(classFromJar)) {
      filteredClassesInPackage.add(classFromJar);
    }
  }
  return filteredClassesInPackage;
}
项目:minnal    文件:AbstractScanner.java   
public void scan(Listener<Class<?>> listener) {
    try {
        ClassPath path = ClassPath.from(classLoader);
        for (String packageName : packages) {
            for (ClassInfo classInfo : path.getTopLevelClassesRecursive(packageName)) {
                Class<?> clazz = classLoader.loadClass(classInfo.getName());
                if (match(clazz)) {
                    listener.handle(clazz);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        // TODO Handle exception
    }
}
项目:ScoreboardStats    文件:ReplaceManager.java   
private void addDefaultReplacers() {
    Set<String> defaultReplacers = Sets.newHashSet();
    try {
        defaultReplacers = ClassPath.from(getClass().getClassLoader())
                .getTopLevelClasses("com.github.games647.scoreboardstats.defaults")
                .stream()
                .map(ClassInfo::load)
                .filter(DefaultReplacers.class::isAssignableFrom)
                .map(clazz -> (Class<DefaultReplacers<?>>) clazz)
                .filter(this::registerDefault)
                .map(Class::getSimpleName)
                .collect(Collectors.toSet());
    } catch (IOException ioEx) {
        logger.error("Failed to register replacers", ioEx);
    }

    logger.info("Registered default replacers: {}", defaultReplacers);
}
项目:PetiteRPC    文件:ProviderContext.java   
private void initProviders() {
    ClassPath classPath;
    try {
        classPath = ClassPath.from(ProviderContext.class.getClassLoader());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Set<ClassInfo> classInfos = classPath.getTopLevelClassesRecursive(basePackage);

    for (ClassInfo classInfo : classInfos) {

        Class<?> clazz = classInfo.load();
        if (clazz.getAnnotation(Provider.class) == null) {
            continue;
        }

        Class<?>[] interfaces = clazz.getInterfaces();
        if (interfaces == null || interfaces.length == 0) {
            throw new RuntimeException("Must implement interface");
        }

        Object providerInstance = objenesis.newInstance(clazz);
        providerContainer.register(interfaces[0], providerInstance);
        registry.register(new Registration(NetUtils.getLocalAddress(), port, interfaces[0].getName()));
    }

}
项目:guava-mock    文件:ClassPathTest.java   
private static ClassPath.ClassInfo findClass(
    Iterable<ClassPath.ClassInfo> classes, Class<?> cls) {
  for (ClassPath.ClassInfo classInfo : classes) {
    if (classInfo.getName().equals(cls.getName())) {
      return classInfo;
    }
  }
  throw new AssertionError("failed to find " + cls);
}
项目:fpm    文件:NaturalEarth2Pbf.java   
public void run() throws IOException {
    for (ClassInfo clazz : shapefiles()) {
        log.info("Converting {}", clazz.getSimpleName());
        NaturalEarthShapefile instance = (NaturalEarthShapefile) injector.getInstance(clazz.load());
        instance.serialize(serializer);
    }
    serializer.close();
}
项目:fpm    文件:NaturalEarth2Pbf.java   
public List<ClassInfo> shapefiles() throws IOException {
    return ClassPath.from(getClass().getClassLoader())
            .getTopLevelClasses(getClass().getPackage().getName() + ".shapefiles").stream()
            .filter(clazz -> NaturalEarthShapefile.class.isAssignableFrom(clazz.load()))
            .sorted(comparing(ClassInfo::getSimpleName))
            .collect(toList());
}
项目:fpm    文件:Tomtom2Osm.java   
public Optional<String> run() throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    log.info("Start generating {}", outputZone);
    new File(outputZone).mkdirs();

    List<String> profileShapeFiles = newArrayList();

    for (ClassInfo clazz : shapefiles()) {
        log.info("Converting {}", clazz.getSimpleName());
        TomtomShapefile shapefile = (TomtomShapefile) injector.getInstance(clazz.load());
        if (shapefile.getFile().exists()) {
            shapefile.serialize(outputZone);
            profileShapeFiles.add(shapefile.getOutputFile());
        } else {
            log.info("No input file found");
        }
    }

    if (profileShapeFiles.isEmpty()) {
        return empty();
    }

    osmMerger.merge(profileShapeFiles, outputZone + OSM_SUFFIX);
    log.info("Done generating {} in {}", outputZone + OSM_SUFFIX, stopwatch);

    stopwatch.reset();
    stopwatch.start();

    splitter.run();
    log.info("Done splitting {} in {}", outputZone, stopwatch);

    return of(outputZone + OSM_SUFFIX);
}
项目:calcite-avatica    文件:TestRunner.java   
/**
 * Finds all tests to run for the TCK.
 *
 * @return A list of test classes to run.
 */
List<Class<?>> getAllTestClasses() {
  try {
    ClassPath cp = ClassPath.from(getClass().getClassLoader());
    ImmutableSet<ClassInfo> classes =
        cp.getTopLevelClasses("org.apache.calcite.avatica.tck.tests");

    List<Class<?>> testClasses = new ArrayList<>(classes.size());
    for (ClassInfo classInfo : classes) {
      if (classInfo.getSimpleName().equals("package-info")) {
        continue;
      }
      Class<?> clz = Class.forName(classInfo.getName());
      if (Modifier.isAbstract(clz.getModifiers())) {
        // Ignore abstract classes
        continue;
      }
      testClasses.add(clz);
    }

    return testClasses;
  } catch (Exception e) {
    LOG.error("Failed to instantiate test classes", e);
    Unsafe.systemExit(TestRunnerExitCodes.TEST_CASE_INSTANTIATION.ordinal());
    // Unreachable..
    return null;
  }
}
项目:googles-monorepo-demo    文件:ClassPathTest.java   
private static ClassPath.ClassInfo findClass(
    Iterable<ClassPath.ClassInfo> classes, Class<?> cls) {
  for (ClassPath.ClassInfo classInfo : classes) {
    if (classInfo.getName().equals(cls.getName())) {
      return classInfo;
    }
  }
  throw new AssertionError("failed to find " + cls);
}
项目:wizards-of-lua    文件:LuaClasses.java   
private Iterable<Class<?>> findClasses() {
  try {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    ClassPath classpath = ClassPath.from(classloader);
    ImmutableSet<ClassInfo> xx = classpath.getTopLevelClassesRecursive(CLASSES_PACKAGE);
    Iterable<ClassInfo> yy = Iterables.filter(xx, input -> isLuaClass(input));
    return Iterables.transform(yy, ClassInfo::load);
  } catch (IOException e) {
    throw new UndeclaredThrowableException(e);
  }
}
项目:wizards-of-lua    文件:WolTestEnvironment.java   
private Iterable<Class<?>> findTestClasses() {
  try {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    ClassPath classpath = ClassPath.from(classloader);
    ImmutableSet<ClassInfo> xx = classpath.getTopLevelClassesRecursive("net.wizardsoflua.tests");
    Iterable<ClassInfo> yy = Iterables.filter(xx, input -> hasTestMethod(input));
    return Iterables.transform(yy, ClassInfo::load);
  } catch (IOException e) {
    throw new UndeclaredThrowableException(e);
  }
}
项目:wizards-of-lua    文件:WolTestEnvironment.java   
private boolean hasTestMethod(ClassInfo input) {
  Class<?> cls = input.load();
  Method[] mm = cls.getDeclaredMethods();
  for (Method method : mm) {
    if (method.getAnnotation(org.junit.Test.class) != null) {
      return true;
    }
  }
  return false;
}
项目:jelenium    文件:Scanner.java   
private static Stream<Class<?>> load( ClassInfo ci ) {
   try {
      return Stream.of( ci.load() );
   } catch ( Throwable ex ) {
      return Stream.empty();
   }
}
项目:business-flows    文件:PublicApiTest.java   
private static List<Class<?>> classesInPackage(String packageName) throws IOException {
    return ClassPath.from(PublicApiTest.class.getClassLoader())
            .getTopLevelClasses(packageName)
            .stream()
            .map(ClassInfo::load)
            .filter(PublicApiTest::notATestClass)
            .sorted(comparing(Class::getName))
            .collect(toList());
}
项目:runelite    文件:PluginManagerTest.java   
@Before
public void before() throws IOException
{
    RuneLite.setOptions(mock(OptionSet.class));

    Injector injector = Guice.createInjector(new RuneLiteModule(),
        BoundFieldModule.of(this));
    RuneLite.setInjector(injector);

    runelite = injector.getInstance(RuneLite.class);
    runelite.setGui(clientUi);
    runelite.setNotifier(notifier);

    // Find plugins we expect to have
    pluginClasses = new HashSet<>();
    Set<ClassInfo> classes = ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive(PLUGIN_PACKAGE);
    for (ClassInfo classInfo : classes)
    {
        Class<?> clazz = classInfo.load();
        PluginDescriptor pluginDescriptor = clazz.getAnnotation(PluginDescriptor.class);
        if (pluginDescriptor != null)
        {
            pluginClasses.add(clazz);
        }
    }

}
项目:nbone    文件:ClassTest.java   
public static void main(String[] args) {

    try {
        ClassPath  classPath = ClassPath.from(ClassTest.class.getClassLoader());
        System.out.println(classPath.getResources());

        for (ClassInfo classInfo : classPath.getTopLevelClasses("java")) {
            System.out.println(classInfo.getName());
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

}
项目:Alchemy    文件:CommandMakeLang.java   
@Override
public void execute(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException {
    if (args.length > 0)
        try {
            String name = Joiner.on(' ').join(args);
            File file = new File(AlchemyModLoader.mc_dir, "mods/" + name);
            if (file.exists() && !file.isDirectory()) {
                ClassLoader loader = new URLClassLoader(new URL[]{ file.toURI().toURL() }, null);
                ClassPath path = ClassPath.from(loader);
                StringBuilder builder = new StringBuilder();
                for (ClassInfo info : path.getAllClasses()) {
                    ClassReader reader = new ClassReader(info.getName());
                    ClassWriter writer = new ClassWriter(0);
                    ClassNode node = new ClassNode(ASM5);
                    reader.accept(node, 0);
                    for (MethodNode method : node.methods) {
                        int index = 0;
                        for (Iterator<AbstractInsnNode> iterator = method.instructions.iterator(); iterator.hasNext();) {
                            AbstractInsnNode insn = iterator.next();
                            if (insn instanceof LdcInsnNode) {
                                LdcInsnNode ldc = (LdcInsnNode) insn;
                                if (ldc.cst instanceof String)
                                    builder.append('-').append(info.getName()).append('#').append(method.name).append('@')
                                    .append(index++).append('=').append(((String) ldc.cst).replace("\n", "\\n")).append('\n');
                            }
                        }
                    }
                }
                File dir = new File(AlchemyModLoader.mc_dir, "lang"),
                        lang = new File(AlchemyModLoader.mc_dir, "lang/" + file.getName() + ".lang");
                if (!dir.exists())
                    dir.mkdirs();
                Tool.save(lang, builder.toString());
            } else
                sender.addChatMessage(new TextComponentString(file.getCanonicalPath() + "not found."));
        } catch(Exception e) { e.printStackTrace(); }
}