Re: Getting a list of Classes in a Package
Omega wrote:
At that point, even the functionality of getting the names of classes
only retrieved by the classloader within the package would suffice.
Instrumenting your program with own Java-agent might be another step
toward computing that.
See (together with its class's package documentation):
<http://java.sun.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getAllLoadedClasses()>
If you know the class-loader (or loaders) classes from your package
should be initiated by, possibly faster would be using
getInitiatedClasses().
Another possible solution using instrumentation is to implement
ClassFileTransformer -- /retransformation incapable/ is enough -- which
will cache (probably weekly) the classes from your package, and then, on
later request, will return them.
During run-time, how do I create one instance of each class in a
package when all I know at compile-time is the package's name?
In general, you can't do that. One (not only) reason, there is no way
to refer a class which not exist yet -- classes might be generated even
at runtime.
BTW -- It's usually preferred by me (hope, I'm not alone with that) to
use, and maintain the application configured using clearly defined, not
hidden /names/ (like class-names, paths, etc.), than the one with some
sophisticated, coded in application, configuration lookup algorithms.
It's then often enough for me to use reflection for user
configurable/extendable parts of code. The solution is usually as easy
as defining an interface (or abstract base class) for extra pluggable
code, e.g.
public interface Plugin {
void hello();
}
and using it as follows:
Plugin pluginInstance = Class.forName(pluginClassName)
.asSubclass(Plugin.class).newInstance();
pluginInstance.hello();
...
Eventually, consider using some more advanced plug-in framework, for
example JPF <http://jpf.sourceforge.net/>.
piotr