io.github.classgraph.ClassInfoList Java Examples

The following examples show how to use io.github.classgraph.ClassInfoList. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VaadinVerticle.java    From vertx-vaadin with MIT License 6 votes vote down vote up
private void registerHandledTypes(ScanResult scanResult, Class<?> initializerClass, Map<Class<?>, Set<Class<?>>> map) {

        HandlesTypes handledTypes = initializerClass.getAnnotation(HandlesTypes.class);
        if (handledTypes != null) {
            Function<Class<?>, ClassInfoList> classFinder = type -> {
                if (type.isAnnotation()) {
                    return scanResult.getClassesWithAnnotation(type.getCanonicalName());
                } else if (type.isInterface()) {
                    return scanResult.getClassesImplementing(type.getCanonicalName());
                } else {
                    return scanResult.getSubclasses(type.getCanonicalName());
                }
            };

            Set<Class<?>> classes = Stream.of(handledTypes.value())
                .map(classFinder)
                .flatMap(c -> c.loadClasses().stream())
                .collect(Collectors.toSet());

            if (!classes.isEmpty()) {
                map.put(initializerClass, classes);
            }
        }
    }
 
Example #2
Source File: ClassGraphUtil.java    From xian with Apache License 2.0 6 votes vote down vote up
/**
 * Reflection is not thread-safe scanning the jars files in the classpath,
 * must be synchronized otherwise a "java.lang.IllegalStateException: zip file closed" is thrown.
 */
synchronized public static <T> Set<ClassInfo> getNonAbstractSubClassInfoSet(Class<T> parentClass, String... packageNames) {
    if (packageNames == null || packageNames.length == 0) {
        packageNames = defaultPackages();
    }
    try (ScanResult scanResult =
                 new ClassGraph()
                         .enableAllInfo()
                         .whitelistPackages(packageNames)
                         .scan()) {
        ClassInfoList classInfos = parentClass.isInterface() ?
                scanResult.getClassesImplementing(parentClass.getName()) :
                scanResult.getSubclasses(parentClass.getName());
        return classInfos
                .stream()
                .filter(classInfo -> !classInfo.isAbstract())
                .collect(Collectors.toSet());
    }
}
 
Example #3
Source File: CollectionDiffer.java    From milkman with MIT License 5 votes vote down vote up
static List<Class<?>> getSubTypesOf(String superclassName) {
    try (ScanResult scanResult = new ClassGraph()
    							 	.enableClassInfo().enableAnnotationInfo()
						 			.ignoreClassVisibility()
						 			.blacklistModules("*")
						 			.scan()) {
        ClassInfoList classInfoList = scanResult.getSubclasses(superclassName);
        return classInfoList.loadClasses();
    }
}
 
Example #4
Source File: ClassGraphUtil.java    From xian with Apache License 2.0 5 votes vote down vote up
public synchronized static ClassInfoList getWithAnnotatedClassInfoList(Class<? extends Annotation> annotationClass, String... packageNames) {
    if (packageNames == null || packageNames.length == 0) {
        packageNames = defaultPackages();
    }
    try (ScanResult scanResult =
                 new ClassGraph()
                         .enableAllInfo()
                         .whitelistPackages(packageNames)
                         .scan()) {
        return scanResult.getClassesWithAnnotation(annotationClass.getName());
    }
}
 
Example #5
Source File: GenerateCodeTask.java    From gradle-plugins with MIT License 5 votes vote down vote up
@TaskAction
public void generate() {

    ScanResult scan = new ClassGraph()
            .overrideClasspath(codeGeneratorClasspath)
            .enableClassInfo()
            .enableAnnotationInfo()
            .scan();
    ClassInfoList classesWithAnnotation = scan.getClassesWithAnnotation(CodeGenerator.class.getCanonicalName());
    ClassInfoList classesImplementing = scan.getClassesImplementing(Generator.class.getCanonicalName());

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Found {} with code generator annotation ({}): ", classesWithAnnotation.size(), CodeGenerator.class.getCanonicalName());
        getLogger().debug(classesWithAnnotation.stream().map(ClassInfo::getName).collect(Collectors.joining(",")));
        getLogger().debug("Found {} implementing {}: ", classesImplementing.size(), Generator.class.getCanonicalName());
        getLogger().debug(classesImplementing.stream().map(ClassInfo::getName).collect(Collectors.joining(",")));
    }

    ProjectContext context = new ProjectContext(getProject().getProjectDir(), inputDir.getAsFile().getOrElse(this.getTemporaryDir()), outputDir.getAsFile().get(), configurationValues.getOrElse(Collections.emptyMap()), sourceSet.getOrElse("none"));

    WorkQueue workQueue = workerExecutor.classLoaderIsolation(spec -> spec.getClasspath().from(codeGeneratorClasspath));

    for (ClassInfo classInfo : classesWithAnnotation) {
        workQueue.submit(UnitOfWork.class, parameters -> {
            parameters.getClassName().set(classInfo.getName());
            parameters.getProjectContext().set(context);
        });
    }
}
 
Example #6
Source File: RewriteAnnotationProviderHandler.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(ScanResult scanResult, File classpathRoot) throws IOException {
	ClassInfoList annotationHandlers = scanResult.getClassesImplementing(REWRITE_ANNOTATION_HANDLER);

	if (annotationHandlers.isEmpty()) {
		return;
	}

	List<String> annotationClassNames = annotationHandlers.stream()
			.map(classInfo -> classInfo.getDeclaredMethodInfo("handles"))
			.flatMap(Collection::stream)
			.map(MethodInfo::getTypeSignature)
			.map(MethodTypeSignature::getResultType)
			.filter(ClassRefTypeSignature.class::isInstance)
			.map(ClassRefTypeSignature.class::cast)
			.map(classRefTypeSignature -> classRefTypeSignature.getTypeArguments().get(0))
			.map(TypeArgument::getTypeSignature)
			.filter(ClassRefTypeSignature.class::isInstance)
			.map(ClassRefTypeSignature.class::cast)
			.map(ClassRefTypeSignature::getFullyQualifiedClassName)
			.collect(Collectors.toList());

	File resultFile = new File(classpathRoot, "META-INF/joinfaces/" + REWRITE_ANNOTATION_HANDLER + ".classes");

	SortedSet<String> result = new TreeSet<>(String::compareTo);

	for (String annotationClassName : annotationClassNames) {
		result.addAll(scanResult.getClassesWithAnnotation(annotationClassName).getNames());
		result.addAll(scanResult.getClassesWithFieldAnnotation(annotationClassName).getNames());
		result.addAll(scanResult.getClassesWithMethodAnnotation(annotationClassName).getNames());
	}

	writeClassList(resultFile, result);
}
 
Example #7
Source File: ServletContainerInitializerHandler.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(ScanResult scanResult, File classpathRoot) throws IOException {
	ClassInfoList scis = scanResult.getClassesImplementing(SERVLET_CONTAINER_INITIALIZER)
			.filter(classInfo -> classInfo.hasAnnotation(HANDLES_TYPES));

	for (ClassInfo sciClassInfo : scis) {
		List<ClassInfo> handledTypes = resolveHandledTypes(sciClassInfo);

		SortedSet<String> classes = findHandledClasses(scanResult, handledTypes);

		File resultFile = new File(classpathRoot, "META-INF/joinfaces/" + sciClassInfo.getName() + ".classes");

		writeClassList(resultFile, classes);
	}
}
 
Example #8
Source File: EntityTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSet<String> getClassNames(ClassInfoList classInfoList) {
  return classInfoList.stream()
      .filter(ClassInfo::isStandardClass)
      .map(ClassInfo::loadClass)
      .filter(clazz -> !clazz.isAnnotationPresent(EntityForTesting.class))
      .map(Class::getName)
      .collect(toImmutableSet());
}
 
Example #9
Source File: GenerateCodeTask.java    From gradle-plugins with MIT License 5 votes vote down vote up
@TaskAction
public void generate() {

    ScanResult scan = new ClassGraph()
            .overrideClasspath(codeGeneratorClasspath)
            .enableClassInfo()
            .enableAnnotationInfo()
            .scan();
    ClassInfoList classesWithAnnotation = scan.getClassesWithAnnotation(CodeGenerator.class.getCanonicalName());
    ClassInfoList classesImplementing = scan.getClassesImplementing(Generator.class.getCanonicalName());

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Found {} with code generator annotation ({}): ", classesWithAnnotation.size(), CodeGenerator.class.getCanonicalName());
        getLogger().debug(classesWithAnnotation.stream().map(ClassInfo::getName).collect(Collectors.joining(",")));
        getLogger().debug("Found {} implementing {}: ", classesImplementing.size(), Generator.class.getCanonicalName());
        getLogger().debug(classesImplementing.stream().map(ClassInfo::getName).collect(Collectors.joining(",")));
    }

    ProjectContext context = new ProjectContext(getProject().getProjectDir(), inputDir.getAsFile().getOrElse(this.getTemporaryDir()), outputDir.getAsFile().get(), configurationValues.getOrElse(Collections.emptyMap()), sourceSet.getOrElse("none"));

    WorkQueue workQueue = workerExecutor.classLoaderIsolation(spec -> spec.getClasspath().from(codeGeneratorClasspath));

    for (ClassInfo classInfo : classesWithAnnotation) {
        workQueue.submit(UnitOfWork.class, parameters -> {
            parameters.getClassName().set(classInfo.getName());
            parameters.getProjectContext().set(context);
        });
    }
}
 
Example #10
Source File: ServletContainerInitializerRegistrationBean.java    From joinfaces with Apache License 2.0 4 votes vote down vote up
@Nullable
protected Set<Class<?>> performClasspathScan() {
	HandlesTypes handlesTypes = AnnotationUtils.findAnnotation(getServletContainerInitializerClass(), HandlesTypes.class);

	if (handlesTypes == null) {
		return null;
	}

	Class<?>[] handledTypes = handlesTypes.value();
	if (handledTypes.length == 0) {
		return null;
	}

	StopWatch stopWatch = new StopWatch(getServletContainerInitializerClass().getName());
	stopWatch.start("prepare");

	ClassGraph classGraph = new ClassGraph()
			.enableClassInfo();

	// Only scan for Annotations if we have to
	if (Arrays.stream(handledTypes).anyMatch(Class::isAnnotation)) {
		classGraph = classGraph.enableAnnotationInfo();
	}

	classGraph = classGraph.enableExternalClasses()
			.enableSystemJarsAndModules() // Find classes in javax.faces
			.blacklistPackages("java", "jdk", "sun", "javafx", "oracle")
			.blacklistPackages("javax.xml", "javax.el", "javax.persistence")
			.blacklistModules("java.*", "jdk.*")
			.filterClasspathElements(path -> {
				log.debug("Path {}", path);
				return true;
			});

	Set<Class<?>> classes = new HashSet<>();

	stopWatch.stop();
	stopWatch.start("classpath scan");

	try (ScanResult scanResult = classGraph.scan()) {

		stopWatch.stop();
		stopWatch.start("collect results");

		for (Class<?> handledType : handledTypes) {
			ClassInfoList classInfos;
			if (handledType.isAnnotation()) {
				classInfos = scanResult.getClassesWithAnnotation(handledType.getName());
			}
			else if (handledType.isInterface()) {
				classInfos = scanResult.getClassesImplementing(handledType.getName());
			}
			else {
				classInfos = scanResult.getSubclasses(handledType.getName());
			}
			classes.addAll(classInfos.loadClasses());
		}

		handleScanResult(scanResult);
	}
	finally {
		stopWatch.stop();
		log.info("Resolving classes for {} took {}s", getServletContainerInitializerClass().getName(), stopWatch.getTotalTimeSeconds());
		if (log.isDebugEnabled()) {
			log.debug(stopWatch.prettyPrint());
		}
	}

	return classes.isEmpty() ? null : classes;
}
 
Example #11
Source File: ClassGraphFacade.java    From easy-random with MIT License 4 votes vote down vote up
private static <T> List<Class<?>> searchForPublicConcreteSubTypesOf(final Class<T> type) {
    String typeName = type.getName();
    ClassInfoList subTypes = type.isInterface() ? scanResult.getClassesImplementing(typeName) : scanResult.getSubclasses(typeName);
    List<Class<?>> loadedSubTypes = subTypes.filter(subType -> subType.isPublic() && !subType.isAbstract()).loadClasses(true);
    return Collections.unmodifiableList(loadedSubTypes);
}