zoukankan      html  css  js  c++  java
  • 如何通过反射获取构造方法

    上次文章说过反射,这次来讲讲如何用反射来获取构造方法。

    获取构造方法:

    1).批量的方法:public Constructor[] getConstructors():

    所有"公有的"构造方法 public Constructor[] getDeclaredConstructors():

    获取所有的构造方法(包括私有、受保护、默认、公有)

    2).获取单个的方法,并调用:public Constructor getConstructor(Class... parameterTypes)

    获取单个的"公有的"构造方法:public Constructor getDeclaredConstructor(Class... parameterTypes)

    获取"某个构造方法"可以是私有的,或受保护、默认、公有。

    调用构造方法:

    Constructor-->newInstance(Object... initargs)

    newInstance是 Constructor类的方法(管理构造函数的类)

    具体代码:

    jdk版本为jdk1.8.0_131

    编程软件为IntelliJ IDEA 2018.3 x64

    实体类:

    public class Person {
    private String name;
    int age;
    public String address;
    public Person(){}
    private Person(String name, int age){
    this.name=name;
    this.age=age;
    }
    public Person(String name, int age, String address){
    this.name=name;
    this.age=age;
    this.address=address;
    }
    }

    测试类:

    import java.lang.reflect.Constructor;

    public class Demo2 {
    public static void main(String[] args) throws ClassNotFoundException {
    //获取Class对象即获取整个Person类
    Class c = Class.forName("获取Class文件对象的三种方式.Person");


    //获取所有public修饰的构造方法
    Constructor[] constructors = c.getConstructors();

    for(Constructor constructor:constructors){
    System.out.println(constructor);
    }

    //获取所有构造方法
    Constructor[] declaredConstructors = c.getDeclaredConstructors();

    for(Constructor declaredConstructor:declaredConstructors){
    System.out.println(declaredConstructor);
    }
    }
    }




    心得感悟:

    耐心不是消极等待,而是像昙花一样地蓄积养分;

    耐心不是贫图安逸,而是像蝉虫一样默默地磨砺自强;

    耐心不是忍气吞声,而是像企鹅一样奋力下潜蓄势。 

    智慧源于勤奋,伟大出自平凡!!!

     

    import java.lang.reflect.Constructor;publicclassReflectDemo2{publicstaticvoidmain(String[] args)throws ClassNotFoundException {//获取Class对象即获取整个Person类 Class c= Class.forName("获取Class文件对象的三种方式.Person");//获取所有public修饰的构造方法 Constructor[] constructors = c.getConstructors();for(Constructor constructor:constructors){ System.out.println(constructor);}//获取所有构造方法 Constructor[] declaredConstructors = c.getDeclaredConstructors();for(Constructor declaredConstructor:declaredConstructors){ System.out.println(declaredConstructor);}}}

  • 相关阅读:
    Mysql存储过程和函数
    python反编译chm文件并生成pdf文件
    python转换html到pdf文件
    python获取系统开机时间
    OpenSL ES: 利用OpenSL ES实现录音功能
    android: 根据文件uri 获取文件名
    Java: InputStream转化为byte数组
    Linux: 查看二进制文件
    Vim: 回到上次编辑的位置
    LayoutInflate: Avoid passing null as the view root
  • 原文地址:https://www.cnblogs.com/dxgld/p/13550103.html
Copyright © 2011-2022 走看看