Zamaroht
Zamaroht

Reputation: 150

Using a HashMap and reflection to call methods with variable argument types

So, I have the following scenario:

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:

  1. 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).

  2. 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

Answers (1)

John
John

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

Related Questions