com.google.common.reflect.ClassPath.from()方法的使用及代码示例

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

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

ClassPath.from介绍

[英]Returns a ClassPath representing all classes and resources loadable from classloader and its ancestor class loaders.

Warning: ClassPath can find classes and resources only from:

  • URLClassLoader instances' file: URLs
  • the ClassLoader#getSystemClassLoader(). To search the system class loader even when it is not a URLClassLoader (as in Java 9), ClassPath searches the files from the java.class.path system property.
    [中]返回一个类路径,该路径表示可从类加载器及其祖先类加载器加载的所有类和资源。
    警告:类路径只能从以下位置查找类和资源:
    *URLClassLoader实例的文件:URL
    *类加载器#getSystemClassLoader()。要搜索系统类加载器,即使它不是URLClassLoader(如在Java9中),ClassPath也会从Java中搜索文件。班路径系统属性。

代码示例

代码示例来源: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: 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: Netflix/zuul

ClassPath cp;
try {
  cp = ClassPath.from(this.getClass().getClassLoader());

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

try {
  ImmutableSet<ClassInfo> pluginPackageSubclasses = ClassPath
    .from(Thread.currentThread().getContextClassLoader())
    .getTopLevelClassesRecursive(PLUGIN_PACKAGE_NAME);

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

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

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

@AndroidIncompatible // Android forbids null parent ClassLoader
// https://github.com/google/guava/issues/2152
public void testJarFileWithSpaces() throws Exception {
 URL url = makeJarUrlWithName("To test unescaped spaces in jar file name.jar");
 URLClassLoader classloader = new URLClassLoader(new URL[] {url}, null);
 assertThat(ClassPath.from(classloader).getTopLevelClasses()).isNotEmpty();
}

代码示例来源: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: Netflix/zuul

ClassPath cp;
try {
  cp = ClassPath.from(this.getClass().getClassLoader());

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

} catch (SecurityException expected) {
ClassPath classPath = ClassPath.from(getClass().getClassLoader());

代码示例来源:origin: deeplearning4j/nd4j

try {
  info = com.google.common.reflect.ClassPath.from(DifferentialFunctionClassHolder.class.getClassLoader())
      .getTopLevelClassesRecursive("org.nd4j.linalg.api.ops");
} catch (IOException e){

代码示例来源: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: runelite/runelite

ClassPath classPath = ClassPath.from(classLoader);

代码示例来源: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: apache/accumulo

ClassPath cp;
try {
 cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader());
} catch (IOException e) {
 throw new RuntimeException(e);

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

classPath = ClassPath.from(loader);
} catch (IOException e) {
  return null;

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

ImmutableSet<ClassInfo> tlc = ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(StringDt.class.getPackage().getName());
for (ClassInfo classInfo : tlc) {
  DatatypeDef def = Class.forName(classInfo.getName()).getAnnotation(DatatypeDef.class);
ImmutableSet<ClassInfo> tlc = ClassPath.from(getClass().getClassLoader()).getTopLevelClasses(thePackageBase + ".composite");
for (ClassInfo classInfo : tlc) {
  DatatypeDef def = Class.forName(classInfo.getName()).getAnnotation(DatatypeDef.class);

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

try {
  components = ClassPath
    .from(VersionPropertyFileGeneratorMojo.class.getClassLoader())
    .getTopLevelClasses()
    .stream()

代码示例来源: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: purplejs/purplejs

private static ClassPath initClassPath()
  {
    try
    {
      return ClassPath.from( ScriptRunner.class.getClassLoader() );
    }
    catch ( final Exception e )
    {
      throw new Error( e );
    }
  }
}

代码示例来源:origin: io.github.splotycode.mosaik/Util

default void registerPackage(String path) {
  try {
    for (ClassPath.ClassInfo classInfo : ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive(path)) {
      Class<?> clazz = classInfo.load();
      if (getObjectClass().isAssignableFrom(clazz)) {
        register((Class<? extends T>) clazz);
      }
    }
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}

相关文章