1

I tried the following code:

constructor = oneClass.getConstructor(new Class[]{String[].class});

return constructor.newInstance(new String[]{"String01","String02"})

(the return Statement return an IllegalArgumentException)

And

Class stringArray = Class.forName("[Ljava.lang.String;");

constructor = oneClass.getConstructor(new Class[]{stringArray})

return constructor.newInstance(new String[]{"String01","String02"})

(the return Statement return an IllegalArgumentException)

How to say that I want to instantiate a constructor with a String[] as argument.

Thank You.

oopbase
  • 11,157
  • 12
  • 40
  • 59
Max
  • 11
  • 1
  • 2
  • possible duplicate of [Problem with constructing class using reflection and array arguments](http://stackoverflow.com/questions/5760569/problem-with-constructing-class-using-reflection-and-array-arguments) – ToYonos Nov 04 '14 at 12:13

2 Answers2

2

What about this :

constructor = oneClass.getConstructor(String[].class);
return constructor.newInstance(new Object[]{new String[]{"String01","String02"}})

Assuming your constructor is like this :

public class OneClass
{
    public OneClass(String[] args)
    {
        // ...
    }
}

Source : Problem with constructing class using reflection and array arguments

Community
  • 1
  • 1
ToYonos
  • 16,469
  • 2
  • 54
  • 70
0

Calling newInstance directly with a new String[] confuses it because it is not sure if that new String[] is one arg, or an alternate way to represent the varargs. By assigning it to an Object "abc" below, it definitely tells the compiler that abc (which represents the String array) is one arg, arg0 to be exact, and not a varargs representing multiple arguments.

import java.lang.reflect.Constructor;

public class Test {
    public Test(String[] args) {
        System.out.println(args);
    }

    public static void main(String[] args) throws Exception {
        Constructor<Test> constructor = Test.class.getConstructor(String[].class);
        new Test(new String[]{});
        Object abc = new String[]{};
        constructor.newInstance(abc);
    }
}
Boon
  • 1,871
  • 1
  • 21
  • 31