My factory class has a collection of classes, I don't want that dependency, when I add a subclass of SuperClass I need the factory file to stay unchanged
edit: My factory class has to return all Superclass's subclasses instances, but I can't have a collections of them (or their names) because that's means I will have to chan开发者_JAVA技巧ge the Factory file whenever I add a new subclass!
package reflection;
public final class Factory {
private final SuperClass[] subclasses_collection
= {new SubClass1(), new SubClass2() /* ...SubClassN */};
public final SuperClass[] getAllSubClasses() {
return subclasses_collection;
}
}
instead of
new SubClass1()
do something like this
Class clazz = Class.forName("SubClass1");
Object subclass1 = clazz.newInstance();
if you want to pass arguments to the constructor, consult this article, section Creating New Objects http://java.sun.com/developer/technicalArticles/ALT/Reflection/
To find all the subclasses of a given class, I would check out this java world site. It goes through a package, loads the classes, and tests them to see if there are any subclasses.
If you want to search for all subclasses of a class, you can use reflection, as Jeffrey says. However, rather than writing the code to do that yourself, or copy-and-pasting it from some random article, i would use ResolverUtil from the Stripes web framework, which does exactly what you want (and more!).
An alternative to classpath scanning would be to build up a registry at runtime. You could create a base class like this:
public abstract class SuperClass {
private static final Set<Class<? extends SuperClass>> SUB_CLASSES = new HashSet<Class<? extends SuperClass>>();
/* instance initializer */ {
SUB_CLASSES.put(getClass());
}
}
Every subclass of that which is instantiated will add itself to the set of subclasses. Your factory can then use that set. All you have to do is ensure that all the subclasses are instantiated at some point - perhaps using a configuration file, or through startup actions of other parts of your system.
精彩评论