zoukankan      html  css  js  c++  java
  • getConstructor、getDeclaredConstructor区别

    getConstructor、getDeclaredConstructor区别

    getDeclaredConstructor:返回指定参数类型、所有声明的(包括private)构造函数

    getConstructor:返回指定参数类型、具有public访问权限的构造函数

    1、 

       /**

         * Returns a Constructor object which represents the constructor matching the given parameter types that is declared by the class represented by this Class.
         * Class[] null is equivalent to the empty array.
         */
        @SuppressWarnings("unchecked")

        public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)

    2、

        /**
         * Returns a Constructor object which represents the public constructormatching the given parameter types.
         * Class[] null is equivalent to the empty array.
         *
         * Use getDeclaredConstructor if you don't want to search superclasses.
         */
        @SuppressWarnings("unchecked")
        public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException

    getDeclaredConstructor:返回指定参数类型、所有声明的(包括private)构造函数

    getConstructor:返回指定参数类型、具有public访问权限的构造函数

    Class中,有其他类似方法。

    反射获取private构造方法

    package com.test;

    A {

        private String str;

        public A() { str = "first";   }

        private A(String str) { this.str = str; }

        public String getStr() { return str;  }

    }

    void main(String[] args) {

        Class cls = Class.forName("com.test.A");

        Class[] paramsType = { String.class };

        Object[] params = { "second" };

        Constructor con = cls.getDeclaredConstructor(paramsType);

        con.setAccessible(true);

        A a = (A)con.newinstanct(params);

        a.getStr();// second

    }

  • 相关阅读:
    ASP.NET操作文件大全
    Jquery1.7中文文档提供下载了
    修改server2005数据库的区分大小写设置
    SQL SERVER 设置自动备份和删除旧的数据库文件
    ASP.NET关闭下载窗口
    DB2通用分页存储过程
    ASP.NET生成压缩文件(rar打包)
    上传文件实体类
    【Demo 0104】注册/注销热键
    【Demo 0018】SEH结束处理程序
  • 原文地址:https://www.cnblogs.com/handsome1013/p/7411559.html
Copyright © 2011-2022 走看看