khernik
khernik

Reputation: 2091

How to create class instance by string name

I want to create new class instance by a string variable, pass int[] as a parameter to this constructor, and save this instance in an array list.

What's more, that class derives from some other class, let's say Bar. And that array list is of type Bar. So:

    List<Bar> something = new ArrayList<Bar>();
    String name = "Foo";
    int[] arr = {1, 2, 3, 4, 5};
    try {
        Class myClass = Class.forName(name);
        Class[] types = {Integer.TYPE};
        Constructor constructor = myClass.getConstructor(types);
        Object[] parameters = {arr};
        Object instanceOfMyClass = constructor.newInstance(parameters);
        something.add(instanceOfMyClass);
    } catch(ClassNotFoundException e) {
        // handle it
    } catch(NoSuchMethodException e) {
        // handle it
    } catch(InstantiationException e) {
        // handle it
    } catch(IllegalAccessException e) {
        // handle it
    } catch(InvocationTargetException e) {
        // handle it
    }

This is what I've came up with, but unfortunately it doesn't work. How can I pass array of integers here (what would be the type)? How can I add this instance to the array list given here (it throws an error that I have to cast the instance of Foo class to Foo class)?

Upvotes: 1

Views: 846

Answers (1)

Jesper
Jesper

Reputation: 206816

Class[] types = {Integer.TYPE};
Constructor constructor = myClass.getConstructor(types);

This looks up a constructor that takes one int or Integer, not an array of ints.

If you want to lookup the constructor that takes an int[], then pass the correct arguments:

Class[] types = { int[].class };
Constructor constructor = myClass.getConstructor(types);

Upvotes: 4

Related Questions