tags:

views:

603

answers:

5

Can I do it with reflection or something like that?

+2  A: 

Yes, the first step is to identify "all" the classes that you cared about. If you already have this information, you can enumerate through each of them and use instanceof to validate the relationship. A related article is here: http://www.javaworld.com/javaworld/javatips/jw-javatip113.html

A: 

Also, if you are writing an IDE plugin (where what you are trying to do is relatively common), then the IDE typically offers you more efficient ways to access the class hierarchy of the current state of the user code.

Uri
+3  A: 

In general, it's expensive to do this. To use reflection, the class has to be loaded. If you want to load every class available on the classpath, that will take time and memory, and isn't recommended.

If you want to avoid this, you'd need to implement your own class file parser that operated more efficiently, instead of reflection. A byte code engineering library may help with this approach.

The Service Provider mechanism is the conventional means to enumerate implementations of a pluggable service. Use the ServiceLoader in Java 6, or implement your own in earlier versions. I provided an example in another answer.

erickson
+3  A: 

What erickson said, but if you still want to do it then take a look at Reflections. From their page:

Using Reflections you can query your metadata for:

  • get all subtypes of some type
  • get all types annotated with some annotation
  • get all types annotated with some annotation, including annotation parameters matching
  • get all methods annotated with some
Peter Severin
A: 

What erikson said is best. Here's a related question and answer thread - http://www.velocityreviews.com/forums/t137693-find-all-implementing-classes-in-classpath.html

The Apache BCEL library allows you to read classes without loading them. I believe it will be faster because you should be able to skip the verification step. The other problem with loading all classes using the classloader is that you will suffer a huge memory impact as well as inadvertently run any static code blocks which you probably do not want to do.

The Apache BCEL library link - http://jakarta.apache.org/bcel/