简体   繁体   中英

How to use varargs as the parameter of Constructor.getConstructor( ) in java

I have a java class like below which I want to create an instance of this class dynamically by using class name.

class Demo {
    public Demo(String... s) {
    //some initialization here.
    }
}

And I want to create an object using following code

Class<?> klass = Class.forName("Demo");

Constructor<?> con = klass.getConstructor("**what should be here**");

Object obj = con.newInstance(param1, param2, ...);

String... is just String[] so you can use

Constructor<?> con = klass.getConstructor(String[].class);

Note that you need to invoke the constructor like

Object o = con.newInstance((Object) new String[] {"first", "second", "more"});

with the cast to (Object) for a varargs invocation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM