views:

115

answers:

3

The title speaks for itself. The language is Java.

+5  A: 

No, you can't, in general. If you could get a complete list of available classes you could check each of them using reflection - but you can't ask a classloader for a list of everything that's available. (For instance, it may be fetching classes over HTTP, and may not know all the files available.)

If you knew that you were interested in classes in a jar file, however, you could open the jar file, find all the class files within it and ask the classloader for those classes. It would be somewhat fiddly.

What's the bigger picture here? There may be a better way to approach the problem.

Jon Skeet
Maybe he's a Smalltalker - this feature is available in all ST environments.
anon
You could do it fairly easily in .NET as well, as you can ask an assembly for all the types it contains.
Jon Skeet
OK I guess my question was a bit too inclusive. I have a method in a class and I need to find all the classes and interfaces up the inheritance hierarchy that also define/implement that method. I was hoping to avoid the tedious crawling up, but I guess I don't have a choice then.
EpsilonVector
How it the type hierarchy that can be shown in eclipse implemented? Surely that is doing something similar to what EpsilonVectoris asking?
mR_fr0g
@EpsilonVector - The "up the inheritance hierarchy" part is important... please edit it into the main question.
Nate
Eclipse knows everything about your program and the runtime.
Thorbjørn Ravn Andersen
+6  A: 

Yes, there is. This is however a tedious and expensive work. You need to crawl through all class files and all JAR files with help of ClassLoader#getResources() and a shot of java.io.File and load all classes of it with help of Class#forName() and finally check if the method is there by Class#getMethod().

However, there are 3rd party API's which can take the tedious work from hands, but it is still expensive, because loading a class would cause its static initializers being executed.

A cleaner way is to make use of annotations and annotate the methods in question and then make use of libraries which searches for classes/methods/fields based on the annotations, such as Google Reflections.

On the other hand, if the entire package name or the JAR file name is known beforehand, then the work will be less tedious and expensive (no need to do stuff recursively nor to load the all of the classes of entire classpath).

Update: I remember, I ever wrote sample code to achieve something like that, you can find it here. It's good to start with, you only need to change it a bit to check the method.

BalusC
+2  A: 

Also, in Eclipse, you can simply ask for this :

Clic on the method, and type Ctrl-T.

KLE