mardi 5 avril 2016

Get variables types from Constructor object (Java Reflection)

I try to create an object out of class class (via java reflection) - user choose a constructor and I need to read variables for this constructor (it supposed to be some of the primitive types).
As you can see this example works only for integer params.

How can I dynamically figure out type of the current argument and read it from the keyboard?

 public static Object chooseConstr(Class cls) throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Scanner keyboard = new Scanner(System.in);

    Constructor[] constructors = cls.getDeclaredConstructors();
    System.out.println("Choose constructor from the list: ");
    System.out.println(Arrays.toString(constructors));

    int constr = keyboard.nextInt();
    constr++;


    Object[] arguments=new Object[constructors[constr].getParameterCount()];

    for(int i=0; i<arguments.length; i++){
        System.out.println("Write argument #"+(i+1));
        arguments[i]=keyboard.nextInt();
    }


    Object object = constructors[constr].newInstance(arguments);

    System.out.println("Object created!");
    return object;
}





Aucun commentaire:

Enregistrer un commentaire