views:

3567

answers:

6

A beginner question about reflection, I suppose:

Is it possible to find all classes or interfaces in a given package? (Quickly looking at e.g. Package, it would seem like no.)

+4  A: 

It is not possible, since all classes in the package might not be loaded, while you always knows package of a class.

Dev er dev
+14  A: 

Due to the dynamic nature off class loaders, this is not possible. Class loaders are not required to tell the VM which classes it can provide, instead they are just handed requests for classes, and have to return a class or throw an exception.

However, if you write your own class loaders, or examine the classpaths and it's jars, it's possible to find this information. This will be via filesystem operations though, and not reflection. There might even be libraries that can help you do this.

If there are classes that get generated, or delivered remotely, you will not be able to discover those classes.

The normal method is instead to somewhere register the classes you need access to in a file, or reference them in a different class. Or just use convention when it comes to naming.

Staale
The inability to query for class names has bugged me for a long time. Sure, it's hard and the performance can vary widely, and for certain classloaders the list is undefined or unbounded, but there are ways this could have been worked around.
Mr. Shiny and New
+9  A: 

You could use this method listed at http://snippets.dzone.com/posts/show/4831, using the Classloader.

Amit
I had a problem with this if my path included spaces. The URL class was escaping spaces to `%20`, but the `new File()` constructor treated that as a literal percent sign two zero. I fixed it by changing the `dirs.add(...)` line to this: `dirs.add(new File(resource.toURI()));` This also meant I had to add `URISyntaxException` to the throws clause of `getClasses`
Kip
A: 

Maybe you could query all classes one-by-one by reflection?

ATorras
If you have all the classes, sure, but the question was: *for a given package, can you find all classes* :-) (And the answer: not using reflection.)
Jonik
A: 

Provided you are not using any dynamic class loaders you can search the classpath and for each entry search the directory or JAR file.

Software Monkey
A: 

More detail discussion about this issue:http://forums.sun.com/thread.jspa?threadID=341935

upson