在java1.9版本中,newInstance()已经被弃用,取而代之的是
class.getDeclaredConstructor().newInstance()
class.newInstance()
会直接调用该类的无参构造函数进行实例化
class.getDeclaredConstructor().newInstance()
getDeclaredConstructor()方法会根据他的参数对该类的构造函数进行搜索并返回对应的构造函数,没有参数就返回该类的无参构造函数,然后再通过newInstance进行实例化。
来个实例:
public class Test {
public Test() {
System.out.println("HelloTest");
}
public static void main(String[] args) throws Exception {
C c = C.class.getDeclaredConstructor(int.class).newInstance(5);
}
}
class C {
public C() {}
private C(int i) {
System.out.println("HelloC" + i);
}
}
感觉就是 class.getDeclaredConstructor().newInstance() 更明确化,明确调用的是哪一个构造器,而不是直接采用默认的无参构造器了。