3

I want to write a simple annotation like "@interface MyClassAnnotation" and "@interface MyMethodAnnotation" that targets Classes and Methods! but the main problem is that on main function i need to list all Class and Method instances on all JVM having that annotations! and I do not want to use any extra libraries, just pure built-in java functions. Can anyone give me a good snippet for it?

Uchiha_Sasuke
  • 309
  • 2
  • 9
  • Already answered? http://stackoverflow.com/questions/659349/how-can-i-find-all-classes-on-the-classpath-that-have-a-specific-method-annotati – ebaxt Mar 04 '12 at 07:50
  • It's not answered really, everyone knows we should use Reflection, the question is HOW? sometimes best answers of StackOverflow are nothing more than question itself. I prefer to report that answer as "intentional ability abuse" instead of marking as best answer :-| – Uchiha_Sasuke Oct 16 '14 at 09:11

2 Answers2

0

You can determine whether your annotation is present on a particular class or method using the getAnnotation element, which is implemented by both Class and java.lang.reflect.Method.

The real question is, which classes and methods do you want to test this on? "All of them" is a bit hard to define. There doesn't seem to be a way to enumerate all of the classes that have been loaded by the JVM.

Taymon
  • 24,950
  • 9
  • 62
  • 84
  • 2
    I want to create something like tomcat! apache tomcat on loading can find all servlet classes that have @WebServlet annotation and keep their url-mapping to map incoming connections to servlets, i want to find all classes having some annotation in classpath – Uchiha_Sasuke Mar 04 '12 at 09:10
0

It's not feasible to go through all classes, you have to somehow narrow the scope. Either provide a configurable list of packages in which the classes with your particular annotation may be in or use the ServiceLoader concept in Java to declare the set of classes you need to find (this is useful if the code loading the service may be know about or link against all the implementations).

ehrencrona
  • 6,102
  • 1
  • 18
  • 24