當前位置: 首頁>>代碼示例>>Java>>正文


Java ClassPath類代碼示例

本文整理匯總了Java中com.google.common.reflect.ClassPath的典型用法代碼示例。如果您正苦於以下問題:Java ClassPath類的具體用法?Java ClassPath怎麽用?Java ClassPath使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ClassPath類屬於com.google.common.reflect包,在下文中一共展示了ClassPath類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: loadClassesInPackage

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
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;
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:20,代碼來源:AbstractPackageSanityTests.java

示例2: getAnnotatedClasses

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
public static Set<Class<?>> getAnnotatedClasses(final Class[] annotations, final String... packages) {
    Set<String> annotationsToScan = Stream.of(annotations).map(Class::getSimpleName).collect(toSet());

    ClassLoader cl = AnnotationScanner.class.getClassLoader();
    try {
        ClassPath cp = ClassPath.from(cl);
        return Stream.of(packages)
            .flatMap(packageName -> cp.getTopLevelClassesRecursive(packageName).stream())
            .filter(isClassAnnotatedByScannedAnnotations(annotationsToScan))
            .map(ClassPath.ClassInfo::load)
            .collect(toSet());
    } catch (IOException e) {
        log.error("Failed to get annotated classes", e);
        return Collections.emptySet();
    }
}
 
開發者ID:Comcast,項目名稱:redirector,代碼行數:17,代碼來源:AnnotationScanner.java

示例3: hasAccessibleConstructor

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
boolean hasAccessibleConstructor(ClassPath.ClassInfo info, String fromPackage) {
    Class<?> load = info.load();
    boolean isPublicClass = Modifier.isPublic(load.getModifiers()),
            isSamePackage = fromPackage.equals(info.getPackageName());

    for (Constructor<?> candidate : load.getDeclaredConstructors()) {
        int modifiers = candidate.getModifiers();

        if (isPublicClass && Modifier.isPublic(modifiers)) return true;
        else if (isSamePackage
                && !Modifier.isPrivate(modifiers)
                && !Modifier.isProtected(modifiers)) return true;
    }

    return false;
}
 
開發者ID:georgewfraser,項目名稱:vscode-javac,代碼行數:17,代碼來源:ClassPathIndex.java

示例4: findMessageClasses

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
@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);
  }
}
 
開發者ID:wizards-of-lua,項目名稱:wizards-of-lua,代碼行數:22,代碼來源:WolTestEnvironment.java

示例5: setClassesInProject

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
private void setClassesInProject(URLClassLoader urlClassLoader) {
    classesInProject = new HashSet<>();
    Set<String> topLevelPackages = getTopLevelPackages();
    if (topLevelPackages == null)
        return;
    for (String packageInProject : topLevelPackages) {
        try {
            Set<ClassPath.ClassInfo> classesInCurrentPackage = ClassPath.from(urlClassLoader).getTopLevelClassesRecursive(packageInProject);
            for (ClassPath.ClassInfo classInfo : classesInCurrentPackage) {
                classesInProject.add(classInfo.load());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
開發者ID:tudorv91,項目名稱:SparkJNI,代碼行數:17,代碼來源:CurrentProjectClassRetriever.java

示例6: getClasses

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
@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);
	}
}
 
開發者ID:domisum,項目名稱:AuxiliumLib,代碼行數:24,代碼來源:ClassUtil.java

示例7: unpackDummyResources

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
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);
        }
    });
}
 
開發者ID:allure-framework,項目名稱:allure2,代碼行數:18,代碼來源:TestData.java

示例8: getCheckstyleModulesRecursive

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:rnveach,項目名稱:checkstyle-backport-jre6,代碼行數:27,代碼來源:CheckUtil.java

示例9: get

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
/**
 * @param basePackage base package for the factory to avoid scanning the whole classpath
 * @return list of factories
 */
@SuppressWarnings("unchecked")
public List<Class<? extends FactoryBase>> get(String basePackage) {
    List<Class<? extends FactoryBase>> result = new ArrayList<>();
    try {
        for (ClassPath.ClassInfo classInfo : ClassPath.from(ClasspathBasedFactoryProvider.class.getClassLoader()).getAllClasses()) {
            if (classInfo.getName().startsWith(basePackage)) {
                Class<?> clazz = classInfo.load();
                if (FactoryBase.class.isAssignableFrom(clazz) && clazz != FactoryBase.class) {
                    result.add((Class<FactoryBase>) clazz);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return result;
}
 
開發者ID:factoryfx,項目名稱:factoryfx,代碼行數:23,代碼來源:ClasspathBasedFactoryProvider.java

示例10: loadAllProvider

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
@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);
			}
		}
}
 
開發者ID:NekoCaffeine,項目名稱:Alchemy,代碼行數:18,代碼來源:AlchemyTransformerManager.java

示例11: getClasses

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
public <T> List<Class<? extends T>> getClasses(Class<T> superType) throws IOException {
    classPath = ClassPath.from(this.getClass().getClassLoader());
    ImmutableSet<ClassPath.ClassInfo> classInfos = classPath.getTopLevelClasses(packageName);

    List<Class<? extends T>> classes = new ArrayList<>();

    for (ClassPath.ClassInfo classInfo : classInfos) {
        if (classInfo.load().isAnnotationPresent(annotationType)) {
            try {
                classes.add(classInfo.load().asSubclass(superType));
            } catch (ClassCastException ex) {
                //Checks that the class is castable before casring it.
            }
        }
    }

    return classes;
}
 
開發者ID:Luke-Melaia,項目名稱:Series-Freak,代碼行數:19,代碼來源:TypeLoader.java

示例12: getAllCommandClasses

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:google,項目名稱:nomulus,代碼行數:25,代碼來源:RegistryToolTest.java

示例13: getAllModels

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
public Collection<Class> getAllModels() throws IOException {
	Class<Charge> chargeClass = Charge.class;
	ClassPath classPath = ClassPath.from(chargeClass.getClassLoader());
	ImmutableSet<ClassPath.ClassInfo> topLevelClasses = classPath.getTopLevelClasses(chargeClass.getPackage().getName());
	List<Class> classList = Lists.newArrayListWithExpectedSize(topLevelClasses.size());
	for (ClassPath.ClassInfo classInfo : topLevelClasses) {
		Class c = classInfo.load();
		// Skip things that aren't APIResources
		if (!APIResource.class.isAssignableFrom(c)) {
			continue;
		}
		// Skip the APIResource itself
		if (APIResource.class == c) {
			continue;
		}
		classList.add(classInfo.load());
	}
	return classList;
}
 
開發者ID:payjp,項目名稱:payjp-java,代碼行數:20,代碼來源:StandardizationTest.java

示例14: loadClassesInPackage

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
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;
}
 
開發者ID:sander120786,項目名稱:guava-libraries,代碼行數:20,代碼來源:AbstractPackageSanityTests.java

示例15: serializableClassesMustDefineSerialVersionUID

import com.google.common.reflect.ClassPath; //導入依賴的package包/類
@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());
}
 
開發者ID:digipost,項目名稱:digg,代碼行數:23,代碼來源:SerializableClassesTest.java


注:本文中的com.google.common.reflect.ClassPath類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。