Java教程

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

本文主要是介绍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");
    }
}

得到的结果

image-20211129102651601

这篇关于Java反射 - getDeclaredConstructor().newInstance()得到实例化对象的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!