mercredi 11 mars 2015

Ask user to input parameters of constructor?

So I'm using reflection to construct a class that the user defines; I ask the user for the name of the class, and how many parameters the preferred constructor of the class has.


Then, the program finds the correct constructor to use. That all works fine, and here is the relevant part of my code:



Object[] params = new Object[numParams];

Class<?>[] paramTypes = ctor.getParameterTypes();

for (int i = 0; i < numParams; i++) {
System.out.format("Enter a value of type %s.\n", paramTypes[i].getName());
params[i] = sc.nextLine();
paramTypes[i].cast(params[i]);
}


numParams is the amount of parameters in the specified constructor, ctor.


So, as you can see, I ask the user to input a variable of type that's specified by the type of the parameter in the constructor.


The type outputs fine (for instance, if the first argument of the constructor is an int, the program says, Enter a value of type int..


However, once a value is entered and the enter key is pressed, I usually get a class cast exception. My end goal is to use the array params to construct a new object of the specified class.


How would I appropriately cast the user input to the expected type?






Aucun commentaire:

Enregistrer un commentaire