java getDeclaredConstructor().newInstance() 方法

1 getDeclaredConstructor

getDeclaredConstructor()返回指定参数类型的privatepublic构造器。

对于getDeclaredConstructor方法获得的构造器需要先设置可访问,再实例化对象。

public class Test {
public Test() {
System.out.println("HelloTest");
}
public static void main(String[] args) throws Exception {
Constructor c = C.class.getDeclaredConstructor(int.class);
c.setAccessible(true);
c.newInstance(5);
}
}

class C {
public C() {}
private C(int i) {System.out.println("HelloC" + i);}
{System.out.println("I'm C class");}
static {System.out.println("static C");}
}

控制台输出

static C
I’m C class
HelloC5

2 newInstance

通过 Class 类的 newInstance() 方法创建对象,该方法要求该 Class 对应类有无参构造方法。执行 newInstance()方法实际上就是使用对应类的无参构造方法来创建该类的实例,其代码的作用等价于Super sup = new Super()

            Class c = Class.forName("Super");
//通过Class类的newInstance()方法创建对象
Super sup = (Super)c.newInstance();
System.out.println(sup.supPublic());

如果 Super 类没有无参构造方法,运行程序时则会抛出一个 InstantiationException 实例化异常。

3 clazz.getDeclaredConstructor().newInstance()

clazz.getDeclaredConstructor().newInstance() 方法和 class.newInstance() 方法实例化对象的区别

3.1 区别

  • class.newInstance() 会直接调用该类的无参构造函数进行实例化
  • getDeclaredConstructor()方法会根据他的参数对该类的构造函数进行搜索并返回对应的构造函数,没有参数就返回该类的无参构造函数,然后再通过newInstance进行实例化。
  • class.getDeclaredConstructor().newInstance() 实例化还可以调用静态类和构造参数

3.2 演示

代码

import java.lang.reflect.InvocationTargetException;

public class Test_1 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
// 反射通过调用无参构造方法构造对象
TestClass testClass = TestClass.class.getDeclaredConstructor().newInstance();
// 反射通过调用有参构造函数构造对象
TestClass testClas1 = TestClass.class.getDeclaredConstructor(int.class).newInstance(6);
System.out.println("==================== newInstance ====================");
TestClass testClass2 = TestClass.class.newInstance();
System.out.println("通过 newInstance 构造的对象:"+testClass2);
}
}


class TestClass{
public TestClass(){}
public TestClass(int value){
System.out.println(value);
}

static {
System.out.println("静态代码块");
}
}

运行结果

静态代码块
6
==================== newInstance ====================
通过 newInstance 构造的对象:com.huke.TestClass@2f4d3709

 
 
 
 
posted @ 2023-06-11 22:26  ImreW  阅读(754)  评论(0编辑  收藏  举报