• 通过反射来创建对象?getConstructor()和getDeclaredConstructor()区别?


    1. 通过类对象调用newInstance()方法,适用于无参构造方法:

       例如:String.class.newInstance()

    public class Solution {
    
        public static void main(String[] args) throws Exception {
    
            Solution solution = Solution.class.newInstance();
    
            Solution solution2 = solution.getClass().newInstance();
    
            Class solutionClass = Class.forName("Solution");
            Solution solution3 = (Solution) solutionClass.newInstance();
    
            System.out.println(solution instanceof Solution); //true
            System.out.println(solution2 instanceof Solution); //true
            System.out.println(solution3 instanceof Solution); //true
        }
        
    }

    2. 通过类对象的getConstructor()getDeclaredConstructor()方法获得构造器(Constructor)对象并调用其newInstance()方法创建对象,适用于无参和有参构造方法。

       例如:String.class.getConstructor(String.class).newInstance("Hello");

    public class Solution {
        //新建一个类
        private String str;
        private int num;
    
        public Solution() {
    
        }
    
        public Solution(String str, int num) {
            this.str = str;
            this.num = num;
        }
    
        public Solution(String str) {
            this.str = str;
        }
    
        public static void main(String[] args) throws Exception {
            //测试上面的新建类
            Class[] classes = new Class[] { String.class, int.class };
            Solution solution = Solution.class.getConstructor(classes).newInstance("hello1", 10);
            System.out.println(solution.str); // hello1
    
            Solution solution2 = solution.getClass().getDeclaredConstructor(String.class).newInstance("hello2");
            System.out.println(solution2.str); // hello2
    
            Solution solution3 = (Solution) Class.forName("Solution").getConstructor().newInstance(); // 无参也可用getConstructor()
            System.out.println(solution3 instanceof Solution); // true
        }
    
    }

    ********* getConstructor()和getDeclaredConstructor()区别:*********

    getDeclaredConstructor(Class<?>... parameterTypes) 
    这个方法会返回制定参数类型的所有构造器,包括public的和非public的,当然也包括private的。
    getDeclaredConstructors()的返回结果就没有参数类型的过滤了。

    再来看getConstructor(Class<?>... parameterTypes)
    这个方法返回的是上面那个方法返回结果的子集,只返回制定参数类型访问权限是public的构造器。
    getConstructors()的返回结果同样也没有参数类型的过滤。

  • 相关阅读:
    一些特效,不断更新
    关于cin输入字符串
    开辟二维数组
    c++ 有关webBrowser控件的一些整理
    WebBrowser 常用方法
    WebRequest和WebBrowser同时登陆,使用同一个sessionID
    delphi 编写的com 对象 用php调用的实例
    Two math problems in http://projecteureka.org sumitted by me.
    delphi dll 实例 与 dll窗体实例
    SSH酒店点菜系统笔记
  • 原文地址:https://www.cnblogs.com/JasonLGJnote/p/11159868.html
Copyright © 2020-2023  润新知