Scan the classpath for classes with custom annotation [duplicate]
For example if I have annotation @MyOwnAnnotation
and have these classes in my classpath, so that I could scan classpath possibly with some kind of filter (example. scan onl开发者_运维问答y packages starting with my.own.app.*
) and get list of all classes with annotation @MyOwnAnnotation
? I'm using guice as injection framework and I don't use Spring.
Yes, check out the Scannotation library.
Also, see the following blog post that documents use of Scannotation.
Basic example:
URL[] urls = ClasspathUrlFinder.findClassPaths(); // scan java.class.path
AnnotationDB db = new AnnotationDB();
db.scanArchives(urls);
Set<String> entityClasses =
db.getAnnotationIndex().get(MyOwnAnnotation.class.getName());
Your annotations will need to have 'runtime' retention so that they are available in the .class
file at runtime.
You could try my library FastClasspathScanner:
List<String> classNames = new FastClassPathScanner("my.own.app")
.scan()
.getNamesOfClassesWithAnnotation(MyOwnAnnotation.class);
I'd actually recommend another approach, better than all others (since they all use classpath scanning, which is slow). It's called ClassIndex and it INDEXES annotated classes:
https://github.com/atteo/classindex
You can try corn-cps
Example:
List<Class<?>> classes = CPScanner.scanClasses(new PackageNameFilter("net.sf.corn.cps.*"),new ClassFilter().appendAnnotation(SampleAnnotation.class));
put the dependecy below in your pom.xml
<dependency>
<groupId>net.sf.corn</groupId>
<artifactId>corn-cps</artifactId>
<version>1.0.1</version>
</dependency>
精彩评论