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

区别

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

演示

代码

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
  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值