开发者

How to create instance of a class with the parameters in the constructor using reflection? [duplicate]

This question already has answers here: Can I use Class.newInstance() with constructor arguments? (9 answers) Closed 8 years ago.

for example:

public class Test {

    public static void main(String[] args) throws Exception {
        Car c= (Car) Class.forName("C开发者_高级运维ar").newInstance();
        System.out.println(c.getName());
    }
}

class Car {
    String name = "Default Car";
    String getName(){return this.name;}
}

clear code.

But, if I add constructor with params, some like this:

public Car(String name)
{this.name = name;}

I see: java.lang.InstantiationException

So, no I don't know, how pass constructor with params.

Please, help.


You need to say which constructor you want to use a pass it arguments.

Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");


If you are handling super / subclasses, or for whatever reason don't know exactly what Class is to be instantiated, the forName() method will be required also:

(ClassName) Class.forName([name_of_the_class])
      .getConstructor([Type]).newInstance([Constructor Argument]);

This assumes name_of_the_class is a passed variable. Also, if the class is in a package, even if that package has been imported, you still have to explicitly stipulate the package in forName() (I think, I'm new to all this).

Class.forName([name_of_package].[name_of_class])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜