com.google.common.reflect.ClassPath类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(10.6k)|赞(0)|评价(0)|浏览(359)

本文整理了Java中com.google.common.reflect.ClassPath类的一些代码示例,展示了ClassPath类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ClassPath类的具体详情如下:
包路径:com.google.common.reflect.ClassPath
类名称:ClassPath

ClassPath介绍

[英]Scans the source of a ClassLoader and finds all loadable classes and resources.

Warning: Current limitations:

  • Looks only for files and JARs in URLs available from URLClassLoader instances or the ClassLoader#getSystemClassLoader().
  • Only understands file: URLs.

In the case of directory classloaders, symlinks are supported but cycles are not traversed. This guarantees discovery of each unique loadable resource. However, not all possible aliases for resources on cyclic paths will be listed.
[中]扫描类加载器的源并查找所有可加载的类和资源。
警告:当前限制:
仅查找URL中的文件和JAR,这些URL可从URLClassLoader实例或ClassLoader#getSystemClassLoader()获得。
只理解文件:URL。
对于目录类加载器,支持符号链接,但不遍历循环。这保证了每个
唯一
可加载资源的发现。但是,不会列出循环路径上资源的所有可能别名。

代码示例

代码示例来源:origin: checkstyle/checkstyle

/**
 * Gets checkstyle's modules (directly, not recursively) in the given packages.
 * @param packages the collection of package names to use
 * @param loader the class loader used to load Checkstyle package names
 * @return the set of checkstyle's module classes
 * @throws IOException if the attempt to read class path resources failed
 * @see #isCheckstyleModule(Class)
 */
public static Set<Class<?>> getCheckstyleModules(
    Collection<String> packages, ClassLoader loader) throws IOException {
  final ClassPath classPath = ClassPath.from(loader);
  return packages.stream()
      .flatMap(pkg -> classPath.getTopLevelClasses(pkg).stream())
      .map(ClassPath.ClassInfo::load)
      .filter(ModuleReflectionUtil::isCheckstyleModule)
      .collect(Collectors.toSet());
}

代码示例来源:origin: checkstyle/checkstyle

/**
 * 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 ModuleReflectionUtil#isCheckstyleModule(Class)
 */
private static Set<Class<?>> getCheckstyleModulesRecursive(
    String packageName, ClassLoader loader) throws IOException {
  final ClassPath classPath = ClassPath.from(loader);
  return classPath.getTopLevelClassesRecursive(packageName).stream()
      .map(ClassPath.ClassInfo::load)
      .filter(ModuleReflectionUtil::isCheckstyleModule)
      .filter(cls -> !cls.getCanonicalName()
          .startsWith("com.puppycrawl.tools.checkstyle.internal.testmodules"))
      .filter(cls -> !cls.getCanonicalName()
          .startsWith("com.puppycrawl.tools.checkstyle.packageobjectfactory"))
      .collect(Collectors.toSet());
}

代码示例来源:origin: google/guava

ClassInfo(String resourceName, ClassLoader loader) {
 super(resourceName, loader);
 this.className = getClassName(resourceName);
}

代码示例来源:origin: google/guava

private List<Class<?>> loadClassesInPackage() throws IOException {
 List<Class<?>> classes = Lists.newArrayList();
 String packageName = getClass().getPackage().getName();
 for (ClassPath.ClassInfo classInfo :
   ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(packageName)) {
  Class<?> cls;
  try {
   cls = classInfo.load();
  } catch (NoClassDefFoundError e) {
   // In case there were linking problems, this is probably not a class we care to test anyway.
   logger.log(Level.SEVERE, "Cannot load class " + classInfo + ", skipping...", e);
   continue;
  }
  if (!cls.isInterface()) {
   classes.add(cls);
  }
 }
 return classes;
}

代码示例来源:origin: syncany/syncany

try {
  ImmutableSet<ClassInfo> pluginPackageSubclasses = ClassPath
    .from(Thread.currentThread().getContextClassLoader())
    .getTopLevelClassesRecursive(PLUGIN_PACKAGE_NAME);
    boolean classNameEndWithPluginSuffix = classInfo.getName().endsWith(PLUGIN_CLASS_SUFFIX);
      Class<?> pluginClass = classInfo.load();

代码示例来源:origin: google/guava

/** Returns all top level classes whose package name is {@code packageName}. */
public ImmutableSet<ClassInfo> getTopLevelClasses(String packageName) {
 checkNotNull(packageName);
 ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
 for (ClassInfo classInfo : getTopLevelClasses()) {
  if (classInfo.getPackageName().equals(packageName)) {
   builder.add(classInfo);
  }
 }
 return builder.build();
}

代码示例来源:origin: google/bundletool

@Test
public void eachSubValidatorIsRegistered() throws Exception {
 // Load sub-classes of SubValidator that live within the same package as top-level classes.
 ImmutableSet<Class<?>> existingSubValidators =
   ClassPath.from(SubValidator.class.getClassLoader())
     .getTopLevelClasses(Reflection.getPackageName(SubValidator.class))
     .stream()
     .map(ClassInfo::load)
     .filter(clazz -> isConcreteSubValidator(clazz))
     .collect(toImmutableSet());
 ImmutableSet<Class<?>> registeredSubValidators =
   ImmutableSet.<Class<?>>builder()
     .addAll(toClasses(AppBundleValidator.BUNDLE_FILE_SUB_VALIDATORS))
     .addAll(toClasses(AppBundleValidator.BUNDLE_SUB_VALIDATORS))
     .addAll(toClasses(BundleModulesValidator.MODULE_FILE_SUB_VALIDATORS))
     .addAll(toClasses(BundleModulesValidator.MODULES_SUB_VALIDATORS))
     .build();
 assertThat(existingSubValidators).containsExactlyElementsIn(registeredSubValidators);
}

代码示例来源:origin: adobe/aem-core-wcm-components

private static List<Class> getClasses(String packageName) throws ClassNotFoundException, IOException {
  List<Class> classes = new ArrayList<>();
  ClassPath classpath = ClassPath.from(AbstractModelTest.class.getClassLoader());
  String packagePrefix = packageName + '.';
  ImmutableSet.Builder<ClassPath.ClassInfo> builder = ImmutableSet.builder();
  classpath.getAllClasses().stream().filter(classInfo -> classInfo.getName().startsWith(packagePrefix)).forEach(builder::add);
  ImmutableSet<ClassPath.ClassInfo> packageClasses = builder.build();
  classes.addAll(packageClasses.stream().map(ClassPath.ClassInfo::load).collect(Collectors.toList()));
  return classes;
}

代码示例来源:origin: jamesagnew/hapi-fhir

/**
 * This is really only useful for unit tests, do not call otherwise
 */
public static void scanEntities(String packageName) throws IOException, ClassNotFoundException {
  ImmutableSet<ClassInfo> classes = ClassPath.from(TestUtil.class.getClassLoader()).getTopLevelClasses(packageName);
  Set<String> names = new HashSet<String>();
  if (classes.size() <= 1) {
    throw new InternalErrorException("Found no classes");
  }
  for (ClassInfo classInfo : classes) {
    Class<?> clazz = Class.forName(classInfo.getName());
    Entity entity = clazz.getAnnotation(Entity.class);
    if (entity == null) {
      continue;
    }
    scanClass(names, clazz, false);
  }
}

代码示例来源:origin: FlowCI/flow-platform

classPath = ClassPath.from(loader);
} catch (IOException e) {
  return null;
ImmutableSet<ClassInfo> classSet = classPath.getTopLevelClassesRecursive(packageName);
Set<Class<?>> classes = new HashSet<>(classSet.size());
    Class<?> aClass = classInfo.load();

代码示例来源:origin: allure-framework/allure2

public static void unpackDummyResources(String prefix, Path output) throws IOException {
  ClassPath classPath = ClassPath.from(TestData.class.getClassLoader());
  Map<String, URL> files = classPath.getResources().stream()
      .filter(info -> info.getResourceName().startsWith(prefix))
      .collect(Collectors.toMap(
          info -> info.getResourceName().substring(prefix.length()),
          ClassPath.ResourceInfo::url)
      );
  files.forEach((name, url) -> {
    Path file = output.resolve(name);
    try (InputStream is = url.openStream()) {
      Files.copy(is, file);
    } catch (IOException e) {
      throw new RuntimeException(String.format("name: %s, url: %s", name, url), e);
    }
  });
}

代码示例来源:origin: com.baidu.hugegraph/hugegraph-common

public static Iterator<ClassInfo> classes(String... packages)
    throws IOException {
  ClassPath path = ClassPath.from(ReflectionUtil.class.getClassLoader());
  ExtendableIterator<ClassInfo> results = new ExtendableIterator<>();
  for (String p : packages) {
    results.extend(path.getTopLevelClassesRecursive(p).iterator());
  }
  return results;
}

代码示例来源:origin: runelite/runelite

ClassPath classPath = ClassPath.from(classLoader);
ImmutableSet<ClassInfo> classes = packageName == null ? classPath.getAllClasses()
  : classPath.getTopLevelClassesRecursive(packageName);
for (ClassInfo classInfo : classes)
  Class<?> clazz = classInfo.load();
  PluginDescriptor pluginDescriptor = clazz.getAnnotation(PluginDescriptor.class);

代码示例来源:origin: osmlab/atlas-checks

.from(Thread.currentThread().getContextClassLoader());
packages.forEach(packageName -> classPath.getTopLevelClassesRecursive(packageName)
    .forEach(classInfo ->
      final Class<?> checkClass = classInfo.load();
      if (checkType.isAssignableFrom(checkClass)
          && !Modifier.isAbstract(checkClass.getModifiers())

代码示例来源:origin: google/guava

public void testNulls() throws IOException {
 new NullPointerTester().testAllPublicStaticMethods(ClassPath.class);
 new NullPointerTester()
   .testAllPublicInstanceMethods(ClassPath.from(getClass().getClassLoader()));
}

代码示例来源:origin: JackOfMostTrades/gadgetinspector

public Collection<ClassResource> getAllClasses() throws IOException {
  Collection<ClassResource> result = new ArrayList<>(getRuntimeClasses());
  for (ClassPath.ClassInfo classInfo : ClassPath.from(classLoader).getAllClasses()) {
    result.add(new ClassLoaderClassResource(classLoader, classInfo.getResourceName()));
  }
  return result;
}

代码示例来源:origin: google/guava

} catch (SecurityException expected) {
ClassPath classPath = ClassPath.from(getClass().getClassLoader());
for (ResourceInfo resource : classPath.getResources()) {
 assertThat(resource.getResourceName()).doesNotContain("com/google/common/reflect/");

代码示例来源:origin: stackoverflow.com

public static void main(String[] args) throws IOException {
  ClassPath p = ClassPath.from(ClassLoader.getSystemClassLoader()); // might need to provide different ClassLoader
  ImmutableSet<ClassInfo> classes = p.getTopLevelClasses("com.example");

  for (ClassInfo classInfo : classes) {
    Class clazz = classInfo.load();
    int modifiers = clazz.getModifiers();
    if (Modifier.isAbstract(modifiers)) {
      System.out.println("Class '" + clazz.getName() + "' is abstract.");
    }
  }
}

代码示例来源:origin: Nextdoor/bender

/**
 * Returns a {@code ClassPath} representing all classes and resources loadable from {@code
 * classloader} and its parent class loaders.
 *
 * <p>Currently only {@link URLClassLoader} and only {@code file://} urls are supported.
 *
 * @throws IOException if the attempt to read class path resources (jar files or directories)
 *         failed.
 */
public static ClassPath from(ClassLoader classloader) throws IOException {
 Scanner scanner = new Scanner();
 for (Map.Entry<URI, ClassLoader> entry : getClassPathEntries(classloader).entrySet()) {
  scanner.scan(entry.getKey(), entry.getValue());
 }
 return new ClassPath(scanner.getResources());
}

代码示例来源:origin: stackoverflow.com

public class OwnerFinder {
  public static void main(String[] args) {
    try {
      ClassPath classPath = ClassPath.from(OwnerFinder.class.getClassLoader());
      classPath.getTopLevelClassesRecursive("com.somepackage")
          .stream()
          .filter(c -> c.getSimpleName().equals("package-info"))
          .map(c -> c.load().getPackage().getAnnotation(PackageOwner.class))
          .forEach(a -> System.out.println(a.owner()));

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

相关文章