I have been working to better understand Java’s reflection tools, and am now trying to create a new instance of a class with a constructor that has been chosen by the user in a drop-down-box.
//ask user what to name the new instance of chosen Class ( passed into this method )
String instanceName = JOptionPane.showInputDialog(null, "Under what name would you like to store this Instance?",
"Create an Instance of a Class", JOptionPane.QUESTION_MESSAGE);
Object chosenC = JOptionPane.showInputDialog(null, "Please choose a Constructor for" + chosenClass,
"Create an Instance of a Class", 3, null, getConstructors(chosenClass), JOptionPane.QUESTION_MESSAGE);
Constructor c = (Constructor)chosenC;
Class[] params = c.getParameterTypes(); //get the parameters of the chosen Constructor
try {
//create the instance with the correct constructor
instance = c.newInstance((Object[])params);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Right now, I get an ArgumentTypeMismatch Exception if I select anything but the default constructor(no parameters). Am I missing something blatantly obvious?
Thank you for any help.
EDIT
Thank you all for your answers.
But then how would I ask for the parameters? If I get the length of the params array, then I would have to determine what type of class each index was and ask the user to input a value in the correct form? Then how would I pass that new array into the newInstance parameter?
Given a class with a constructor like so:
Your code is actually invoking the following:
Where it should be invoking:
You need an instance of each of the constructor parameter types, but you’re only passing classes. Interestingly, if you constructor only takes instances of
Class, it would work, but would give unexpected results.