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 extendAIInstruction. 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 everyAIInstructionsubclass has very different constructors (in types and amount of parameters).I'm not sure either if the
newInstancecall will work, because the params array contains instances of typeObject.
Any help is greatly appreciated, thank you!