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.

1

2 Answers 2

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

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

Comments

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);
    }
}

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.