4

I am looking for an easy way to look through a java package for my own annotation.

What I am trying to do is mark some classes with my own annotation. Every minute a scanner should scan some packages for this annotation.

With scanotation jar I tried that

URL url = ClasspathUrlFinder.findClassBase(FileWatcher.class);

and with AnnotationDB I could check if this class (FileWatcher.class) has the annotation. Now I need a list of classes in order to scan them all.

I read some articles and most people said it is not possible because of the classloader could load external jar files as well.

The other option I have is to copy all EJB Projects containing those annotations inside a subdirectory and scan all those jar files. I think that would might work, but is there no better way?

Many greetings, Hauke

Hauke
  • 1,405
  • 5
  • 23
  • 44

3 Answers3

3

Try using reflections. There are some examples in the test code.

sbridges
  • 24,960
  • 4
  • 64
  • 71
1

Thanks. That helped a lot and it is working very easy. In case somebody needs that:

      String packagename = "de.whatever";

      final Reflections reflections = new Reflections(packagename);

      Set<Class<? extends CargoServiceListenerInterface>> subTypes = reflections.getSubTypesOf(CargoServiceListenerInterface.class);

      for (Class<? extends CargoServiceListenerInterface> class1 : subTypes) {
        System.out.println("Class : " + class1.getName());
      }

Instead of getSubtypes you can call also the annotation method.

If you use maven put this in the pom.xml

    <repositories>
    <repository>
        <id>reflections-repo</id>
        <name>Reflections Maven2 Repository</name>
        <url>http://reflections.googlecode.com/svn/repo</url>
    </repository>
</repositories>

    <dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.5</version>
</dependency>
Hauke
  • 1,405
  • 5
  • 23
  • 44
0

If you want a really light weight (no dependencies, simple API, 15 kb jar file) and very fast solution, take a look at annotation-detector found at https://github.com/rmuller/infomas-asl. Scanning specific packages is very fast (matter of a few ms).

See also question Scanning Java annotations at runtime for other options

Disclaimer: I am the author.

Community
  • 1
  • 1
rmuller
  • 12,062
  • 4
  • 64
  • 92