I have over 250 subclasses that need instances made of them, and I can't sit there and coy and paste new Class();
250 times. Is there anyway using Reflection to make an instnace of the classes? No constructor is needed when making the instance.
Thanks.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
That's a chunk of code to load all the classes of a package, to create new instances for it and to put them in an hashmap (all my classes inherits from Commande):
Here, COMMAND_DIRECTORY is org/commandes for me.
I don't know if this is the right way to do it, but it's the only way i found to implement the Command design pattern (plugin-like implemented) in a servlet.
I really don't undesrtand you, but I try to guess (not tested):
Look at Creating New Class Instances
EDIT: May be http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#forName(java.lang.String)
You can do as follows:
Only works if your classes have only a default constructor, or public zero args constructor. The code may be looped, generalized or reproduced if you need.
For more general solution this may help you understand why it is not possible. You can do whatever you want with any classes you know, or know their name, or can access their name from any source, or be provided with such minimum information in any way.
But without any knowledge of that classes, it is hardly possible. You would have to seek for all classes in current classpath and then chceck their inheritance tree for compliance with your particular class.
First, you'll need to get all the subclasses. That particular answer seems legitimate, though I haven't tested it myself.
Then iterate through the classes and create the instances using either
Class.newInstance
(no-args constructors) orClass.getConstructor
andConstructor.newInstance
when there are parameters for the constructor that you have to pass. The final code will look something like this:This will get the subclasses, iterate over them, and create an instance of each one. There are some exceptions here that I'm not doing anything with. You may also have to do some casting (though I don't think you have to).
Edit: My answer above will apparently cause some spurious class loading. Create your set of subclasses like this instead:
Then these lines:
Become this: