如何搜索带注释类的整个类路径?
我正在创建一个库,希望允许用户注释他们的类,因此当Web应用程序启动时,我需要扫描整个类路径以查找某些注释。
我正在考虑类似于Java EE 5 Web服务或EJB的新功能。你用@WebService或@EJB注释你的类,系统会在加载时找到这些类,这样就可以远程访问它们。
如何搜索带注释类的整个类路径?
我正在创建一个库,希望允许用户注释他们的类,因此当Web应用程序启动时,我需要扫描整个类路径以查找某些注释。
我正在考虑类似于Java EE 5 Web服务或EJB的新功能。你用@WebService或@EJB注释你的类,系统会在加载时找到这些类,这样就可以远程访问它们。
当前回答
谷歌反射,如果你也想发现接口。
Spring ClassPathScanningCandidateComponentProvider没有发现接口。
其他回答
另一个解决方案是朗玛莫的倒影。
快速回顾一下:
如果您正在使用Spring,那么Spring解决方案是最好的选择。否则就是很大的依赖。 直接使用ASM有点麻烦。 直接使用Java Assist也很笨拙。 注释超轻,方便。还没有专家集成。 Reflections索引所有东西,而且非常快。
You can find classes with any given annotation with ClassGraph, as well as searching for other criteria of interest, e.g. classes that implement a given interface. (Disclaimer, I am the author of ClassGraph.) ClassGraph can build an abstract representation of the entire class graph (all classes, annotations, methods, method parameters, and fields) in memory, for all classes on the classpath, or for classes in whitelisted packages, and you can query that class graph however you want. ClassGraph supports more classpath specification mechanisms and classloaders than any other scanner, and also works seamlessly with the new JPMS module system, so if you base your code on ClassGraph, your code will be maximally portable. See the API here.
谷歌反射,如果你也想发现接口。
Spring ClassPathScanningCandidateComponentProvider没有发现接口。
zapp有一篇精彩的评论,回答了所有这些问题:
new Reflections("my.package").getTypesAnnotatedWith(MyAnnotation.class)
在Spring中,您还可以使用AnnotationUtils类编写以下代码。例如:
Class<?> clazz = AnnotationUtils.findAnnotationDeclaringClass(Target.class, null);
要了解更多细节和所有不同的方法,请查看官方文档: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/annotation/AnnotationUtils.html