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 only 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.
Asked
Active
Viewed 7,351 times
15
Donal Fellows
- 126,337
- 18
- 137
- 204
newbie
- 23,730
- 77
- 197
- 300
4 Answers
12
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.
johnstok
- 91,872
- 12
- 52
- 76
-
You may find other - better alternatives here: http://stackoverflow.com/questions/259140/scanning-java-annotations-at-runtime or if you're not hang up on classpath scanning, see my answer below for alternate and faster solution. – LAFK says Reinstate Monica Apr 24 '16 at 09:28
2
You could try my library FastClasspathScanner:
List<String> classNames = new FastClassPathScanner("my.own.app")
.scan()
.getNamesOfClassesWithAnnotation(MyOwnAnnotation.class);
Luke Hutchison
- 7,084
- 2
- 37
- 33
2
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:
LAFK says Reinstate Monica
- 2,690
- 34
- 51
0
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>
Serhat
- 222
- 4
- 2