如何使用反射在构造函数中使用参数创建类的实例? [英] How to create instance of a class with the parameters in the constructor using reflection?
本文介绍了如何使用反射在构造函数中使用参数创建类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
public class Test {
public static void main(String[] args) throws Exception {
Car c= (Car) Class.forName("Car").newInstance();
System.out.println(c.getName());
}
}
class Car {
String name = "Default Car";
String getName(){return this.name;}
}
清除代码.
但是,如果我添加带有参数的构造函数,一些像这样:
But, if I add constructor with params, some like this:
public Car(String name)
{this.name = name;}
我看到:java.lang.InstantiationException
所以,不,我不知道,如何使用参数传递构造函数.
So, no I don't know, how pass constructor with params.
请帮忙.
推荐答案
你需要说明你想使用哪个构造函数来传递它的参数.
You need to say which constructor you want to use a pass it arguments.
Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");
这篇关于如何使用反射在构造函数中使用参数创建类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文