Reputation: 150
So, I have the following scenario:
I have a class named AIInstruction
, which is not actually meant to be instantiated by itself, but trough a child class.
I have a bunch of classes called AIInstruction_***
which extend AIInstruction
. Every single one of these classes has a single constructor, but differ in the type and amount of parameters they need.
And I have a manager class which looks something like this:
public class AIControls
{
public static HashMap<String, Class<? extends AIInstruction>> INSTRUCTION_DICTIONARY = new HashMap<String, Class<? extends AIInstruction>>();
static {
INSTRUCTION_DICTIONARY.put("rotateTowards", AIInstruction_rotateTowards.class);
INSTRUCTION_DICTIONARY.put("moveToPoint", AIInstruction_moveToPoint.class);
// (etc...)
}
LinkedList<AIInstruction> _instruction_queue;
public AIControls()
{
_instruction_queue = new LinkedList<AIInstruction>();
}
public void addInstruction(String instruction, Object... params)
{
/*
???
*/
}
}
What I want to do inside addInstruction
, is creating an instance of the class whose key inside the INSTRUCTION_DICTIONARY
is instruction
, and add this new instance to the _instruction_queue
LinkedList.
The params
varargs are meant to be the parameters that the constructor method of the class reffered to by instruction
needs.
From what I researched, I found that reflection is pretty much the way to go. I have never used reflection before, so I guess I might be missing a thing or two. This is how far I have managed to go:
public void addInstruction(String instruction, Object... params)
{
Class<?> the_class = INSTRUCTION_DICTIONARY.get(instruction);
Constructor<?> the_constructor = the_class.getConstructor(/* ??? */);
AIInstruction new_instruction = the_constructor.newInstance(params);
_instruction_queue.add(new_instruction);
}
However, that code has basically two problems:
I'm not sure what to put in place of the /* ??? */
. I guess I should be putting the types of the parameters, but they could be anything, since every AIInstruction
subclass has very different constructors (in types and amount of parameters).
I'm not sure either if the newInstance
call will work, because the params array contains instances of type Object
.
Any help is greatly appreciated, thank you!
Upvotes: 2
Views: 1099
Reputation: 816
You can use Class.getConstructors()
to get an array of all constructors in the class. Assuming you only have one constructor, you can simply check for size to prevent OOB Exceptions, and save [0] as your Constructor.
It doesn't look like you need to know what type of parameters that constructor takes, but if you do you can always use Constructor.getParameterTypes()
. This could also be used to identify between, as stated before, multiple constructors if that were to be the case.
Upvotes: 1