3

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 now my code 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;
}

1 Answer 1

2

This will be tricky. Of course scanner has some basic methods to read in some types, but if you want to read other kinds of arguments you'll have to figure out a way to read them yourself.

For this, you can use Constructor.getParameterTypes():

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

Class<?>[] pTypes = constructors[constr].getParameterTypes();

for (int i = 0; i < arguments.length; i++) {
    System.out.println("Write argument #" + (i + 1) + ". Of type: "+pTypes[i].getName());

    if(pTypes[i].equals(int.class)) {               
        arguments[i] = keyboard.nextInt(); // read an int
    } else if(pTypes[i].equals(String.class)) {
        arguments[i] = keyboard.next(); // read a String
    } else {
        // custom read code for other types
    }
}
...

Note that the above is not complete, scanner has more methods to read other types too, which I didn't show here.

The best strategy for reading other types of arguments, is probably to read them as a string and convert them to the corresponding objects through some factory method.

Sign up to request clarification or add additional context in comments.

1 Comment

I just noticed that you only need it for primitives, so this should be simpler than I said. Just note that it can works for other types too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.