2011-09-06 39 views
14

例如,如果我有注释@MyOwnAnnotation并在我的类路径中包含这些类,以便我可以使用某种过滤器扫描类路径(例如,只扫描以my.own.app.*开头的包)并获取所有具有注释的课程列表@MyOwnAnnotation?我使用guice作为注入框架,我不使用Spring。使用自定义注释扫描类路径

回答

12

是的,请查看Scannotation库。

另外,请参阅以下博客文章documents use of Scannotation

基本例如:

URL[] urls = ClasspathUrlFinder.findClassPaths(); // scan java.class.path 
AnnotationDB db = new AnnotationDB(); 
db.scanArchives(urls); 
Set<String> entityClasses = 
    db.getAnnotationIndex().get(MyOwnAnnotation.class.getName()); 

注解需要有“运行时的保留,使他们在.class文件在运行时可用。

+0

您可能会发现其他的 - 更好的选择在这里:http://stackoverflow.com/questions/259140/scanning-java-annotations-at-runtime或者如果你在类路径扫描中不会挂断,请参阅下面的答案以获得更多更快的解决方案。 –

0

您可以尝试玉米CPS

例子:

List<Class<?>> classes = CPScanner.scanClasses(new PackageNameFilter("net.sf.corn.cps.*"),new ClassFilter().appendAnnotation(SampleAnnotation.class)); 

放的关系是不低于在你的pom.xml

<dependency> 
    <groupId>net.sf.corn</groupId> 
    <artifactId>corn-cps</artifactId> 
    <version>1.0.1</version> 
</dependency> 
1

你可以试试我的图书馆FastClasspathScanner

List<String> classNames = new FastClassPathScanner("my.own.app") 
    .scan() 
    .getNamesOfClassesWithAnnotation(MyOwnAnnotation.class); 
0

我实际上推荐了另一种方法,比所有其他方法更好(因为它们都使用类路径扫描,这很慢)。这就是所谓的ClassIndex和它索引注释类:

https://github.com/atteo/classindex