1

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)?

3
  • something.add( (Bar) instanceOfMyClass ); Commented Apr 20, 2014 at 17:46
  • What line is throwing the error? What's the stack trace? (Or is this a compile-time error?) Commented Apr 20, 2014 at 17:49
  • Well, it doesn't actually matter, as only these two things were giving errors, and correcting it works, thanks! ;) Commented Apr 20, 2014 at 17:52

1 Answer 1

4
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);
Sign up to request clarification or add additional context in comments.

Comments

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.