Java反射 - getDeclaredConstructor().newInstance()得到实例化对象


Java反射 - getDeclaredConstructor().newInstance()得到实例化对象

  • class.newInstance()实例化只能直接调用构造参数
  • class.getDeclaredConstructor().newInstance()实例化可以调用静态类和构造参数

实现类

public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    UserService.class.getDeclaredConstructor().newInstance();
    System.out.println("=====================");
    UserService.class.newInstance();
}

class对象代码

public class UserService {

    static {
        System.out.println("static");
    }
    
    public UserService() {
        System.out.println("test");
    }
}

得到的结果

202111291240338


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM