Is it possible to get a collection of public inter

2019-06-11 00:10发布

问题:

Is it possible to get a collection of public interfaces and classes in a given package using reflection? Question is for Java 1.6

Why: I have a package where some classes are annotated. I want to collect them automcatically for documenting

回答1:

Do you really have to generate the documentation at runtime? The normal way to use the annotation processing tool (APT): http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/guide/apt/GettingStarted.html



回答2:

No, not possible, at least in general. That's because the classloader mechanism is too flexible to permit it: classes can be loaded via network or generated on the fly, and the only operation is "ask the classloader for a class with fully qualified name X, and it will either return class X or throw an exception. You could easily implement a classloader that returns an class for any name in any package, i.e. an infinite number of classes.

For the specific case of loading classes from a directory or JAR file via an URLClassLoader, it's possible to look at the contents of said directory or JAR file.