15

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.

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
newbie
  • 24,286
  • 80
  • 201
  • 301

4 Answers4

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
  • 96,212
  • 12
  • 54
  • 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 4Monica_banAI_modStrike 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
  • 8,186
  • 2
  • 45
  • 40
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:

https://github.com/atteo/classindex

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