Java SE-reflection mechanism

reflection:

  1. What is reflection?

          You can dynamically view all the attributes and methods of the class (Java objects that have been loaded into the JVM) at runtime, and you can access any methods and attributes of the class at the same time. This method is called reflection.
  

First come a person.class

package reflect;

public class Person {
    //类在计算机语言中 描述现实生活中事物的属性特征和行为

    public String name;
    public String sex;
    private int age;

    //构造方法是为了用来创建对象使用的。主要用于初始化。
    //构造方法是和类名相同,参数不同。
    public Person() {
    }
    private Person(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;

    }

    private void study(){
        System.out.println("我是"+name+"在学习java");
    }

    private void sleep(){
        System.out.println("我是"+name+"我要睡觉了");
    }

    @Override
    public String toString() {
        return "reflect.Person{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }


}

2. How to get the Class object of the class
  

Three ways:

import java.lang.reflect.InvocationTargetException;

public class CreateClassObject {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //加载.class文件,生成Class对象,Class对象的获取方式
       
        //获取Person的Class对象方式一:
        Class clasz = Class.forName("reflect.Person");
        
        //获取Person的Class对象方式二:
        Class clasz1 =Person.class;
        
        //获取Person的Class对象方式三:
        Person person =new Person();
        Class clasz2 =person.getClass();
    }
}


   Three. How to obtain the construction method of the class


       1.clazz.getContructors() Get all public constructors

        Class clasz = Class.forName("reflect.Person");
         
        //获取所有公有的构造方法
        
        //返回值类型是一个Constructor型数组
        Constructor[] constructors = clasz.getConstructors();
        for (Constructor cons : constructors) {
            
            //利用toString()打印结果
            System.out.println(cons.toString());
        }


       2.clazz.getContructor() Get a single public constructor

  //获取单个公有的无参构造方法
        Constructor constructor = clasz.getConstructor();
        System.out.println(constructor);
        Person person2 = (Person) constructor.newInstance();//调用构造方法创建对象
        person2.setName("hh");
        person2.setSex("男");
        person2.setAge(30);
        person2.study();


       3.clazz.getDeclaredContructors() Get all the construction methods (including public and private construction methods)

  //获取所有的公有和私有的构造方法
        Constructor[] consts = clasz.getDeclaredConstructors();
        for (Constructor con : consts) {
            System.out.println(con.toString());
        }


    4. clazz.getDeclaredContructor() Get a single constructor (including public and private constructors)

 //获取私有的构造方法
        Constructor constructor1 = clasz.getDeclaredConstructor(String.class); //传入参数
        System.out.println(constructor1);

        constructor1.setAccessible(true);
            //把私有构造方法设置为可访问的
       
        Person person3 = (Person) constructor1.newInstance("hhh");
        person3.study();

  • When calling private methods , use constructor1.setAccessible (true) ; modifiers can be ignored.


   Four. How to call the constructor to create an object
      

       contructor.newInstance();
       contructor.newInstance("参数");


   Five. How to get member variables
      

       clazz.getFields () // Get all the public properties
       clazz.getField () // Get a single public property
       clazz.getDeclaredFields () // Get all attributes (including public and private property)
       clazz.getDeclaredField () // Get single Properties (including public and private properties)

package reflect;

import java.lang.reflect.Field;

public class CreateFields {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class clasz = Class.forName("reflect.Person");

        //一、获取类的所有公有成员变量
        Field[] fields = clasz.getFields();
        for (Field field : fields) {
            System.out.println(field.toString());
        }

        /*运行结果:public java.lang.String reflect.Person.name
                   public java.lang.String reflect.Person.sex*/

        //二、获取单个公有成员变量
        Field name = clasz.getField("name");
        Field sex = clasz.getField("sex");
        //Field age = clasz.getField("age"); //age为私有变量,运行报错
        System.out.println(name);
        System.out.println(sex);
        //System.out.println(age);

        /*运行结果:public java.lang.String reflect.Person.name
        public java.lang.String reflect.Person.sex*/

        //三、获取所有的变量(包括公有和私有的)
        Field[] fieldsq1 = clasz.getDeclaredFields();
        for (Field field : fieldsq1) {
            System.out.println(field.toString());      //私有变量age也会打印
        }
            System.out.printf(fieldsq1[2].toString()); //只打印age变量

        //四、获取单个公有成员变量
        Field name1 = clasz.getDeclaredField("name"); //出入参数指定某个变量
        Field sex1 = clasz.getDeclaredField("sex");
        Field age1 = clasz.getDeclaredField("age");
        System.out.println(name1);
        System.out.println(sex1);
        System.out.println(age1);
    }
}


 VI. How to obtain


       clazz.getMethods () // Get all the public methods
       clazz.getMethod () // Get a single public method
       clazz.getDeclaredMethods () // Get all methods (including public and private methods)
       clazz.getDeclaredMethod () // Get single Methods (including public and private methods)

package reflect;

import java.lang.reflect.Method;

public class CreateMethods {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
        Class clasz = Class.forName("reflect.Person");

        //一、获取所有的公有方法
        Method[] methods = clasz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
             /*运行结果:(perseon默认继承Object类)
                        public java.lang.String reflect.Person.toString()
                        public java.lang.String reflect.Person.getName()
                        public void reflect.Person.setName(java.lang.String)
                        public void reflect.Person.setAge(int)
                        public void reflect.Person.study()
                        public void reflect.Person.setSex(java.lang.String)
                        public int reflect.Person.getAge()
                        public java.lang.String reflect.Person.getSex()
                        public final void java.lang.Object.wait() throws java.lang.InterruptedException
                        public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
                        public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
                        public boolean java.lang.Object.equals(java.lang.Object)
                        public native int java.lang.Object.hashCode()
                        public final native java.lang.Class java.lang.Object.getClass()
                        public final native void java.lang.Object.notify()
                        public final native void java.lang.Object.notifyAll()*/

         //二、获取单个公有方法
        Method method =clasz.getMethod("study");
        System.out.println(method);
            /*运行结果:public void reflect.Person.study()*/

        //三、获取所有的公有和私有方法
        Method[] methods2 = clasz.getDeclaredMethods();
        for (Method met : methods2) {
            System.out.println(met);
        }
            /*运行结果:私有方法sleep也获取到了,private void reflect.Person.sleep()*/

        //四、获取单个的私有或者公有方法
        Method studyMethod =clasz.getDeclaredMethod("study");
        Method sleepMethod =clasz.getDeclaredMethod("sleep");
        Method getAgeMethod =clasz.getDeclaredMethod("getAge");
        System.out.println(studyMethod);
        System.out.println(sleepMethod);
        System.out.println(getAgeMethod);
       
        /*运行结果: public void reflect.Person.study()
                    private void reflect.Person.sleep()
                    public int reflect.Person.getAge()*/
    }
}

 

Guess you like

Origin blog.csdn.net/Qmilumilu/article/details/104618189