Java: reflection mechanism learning notes

1、 Reflection mechanism

1. Overview

Reflection mechanism: encapsulate each component of a class into other objects. In the running state, you can dynamically obtain class information and call methods of class objects.

2. Advantages and disadvantages

3. Class loading process

The Java language has the excellent characteristics of "compiling at one place and running everywhere", and can well adapt to different platforms. The process is roughly as follows:

2、 Three ways to get class objects

This class object contains all the information of the class, that is, we can access this class in the JVM after obtaining the object of this class. So, how to get it? There are three main ways.

1、Class. Forname ("full class name")

Through the static method forname ("full class name") of class, return the class object of the class corresponding to the full class name.

    //Class.forName("全类名");
    Class cls1 = Class.forName("com.my.base.Person");
    System.out.println(cls1);

2. Class name class

Get through the class attribute of the class name and return the class object corresponding to the class.

    //类名.class;
    Class cls2 = Person.class;
    System.out.println(cls2);

3. Object getClass()

The getClass () method is defined in the object and returns the class object corresponding to the class to which the object belongs.

    //对象.getClass();
    Person p = new Person();
    Class cls3 = p.getClass();
    System.out.println(cls3);

Same bytecode file Class will only be loaded once during a program run, and the class object obtained by either method is the same.

    // == 比较三个对象,都是true

    System.out.println(cls1 == cls2);
    System.out.println(cls1 == cls3);
    System.out.println(cls3 == cls2);

3、 Reflection correlation method

The class object contains all the information of the class, which is encapsulated in Java Under the lang.reflect package, classes are formed one by one. Incomplete statistics are as follows:

Class class provides corresponding methods to obtain this information. Due to many methods, please refer to the official JDK document for details.

Here I summarize some general:

PS: there must be a missing API. When you use it, you'll be done by flipping through the API.

4、 Demo × two

1. Try to write a clone () method yourself

package com.my.reflect.practice;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @auther Summerday
 */

@SuppressWarnings("unchecked")
public class ImplementClone {
    public Object clone(Object o) throws Exception{
        //获取对象的实际类型
        Class<Object> clz = (Class<Object>) o.getClass();

        //获取所有构造方法
        Constructor<Object>[] cs = (Constructor<Object>[]) clz.getDeclaredConstructors();
        //任取一个构造方法
        Constructor<Object> c = cs[0];

        //防止取出构造方法为私有
        c.setAccessible(true);

        //该构造方法参数有or无?

        //获取参数类型
        Class[] ps = c.getParameterTypes();
        //存储参数的数组
        Object[] os = new Object[ps.length];

        for(int i = 0;i<ps.length;i++){
            //判断是否为基本类型
            if(ps[i].isPrimitive()){
                if(ps[i] == boolean.class)
                    os[i] = false;
                else if(ps[i] == char.class)
                    os[i] = '\u0000';
                else
                    os[i] = 0;
            }else{
                os[i] = null;
            }
        }
        //执行构造方法创建对象
        Object obj = c.newInstance(os);

        //获取属性数组
        Field[] fs = clz.getDeclaredFields();

        for (Field f : fs){

            //如果final修饰则返回,无法修改
            if((f.getModifiers()&Modifier.FINAL)!=0){
                continue;
            }
            //暴力破解
            f.setAccessible(true);

            //取出原属性值
            Object value = f.get(o);

            //将取出的属性值赋值给新对象的属性
            f.set(obj,value);
            
        }
        return obj;
    }
}

2. Dynamic loading with configuration file

package com.my.reflect.practice;

/**
 * @auther Summerday
 */

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 *
 *     参考黑马程序员教学视频
 *
 * 实现:1、配置文件  2、反射
 *
 * 一、将需要创建的对象的全类名和需要执行的方法定义在配置文件中
 *
 * 二、在程序中加载读取配置文件
 *
 * 三、使用反射来加载类文件进内存
 *
 * 四、创建对象
 *
 * 五、执行方法
 *
 */
public class ReflectTest {

    public static void main(String[] args) throws Exception {

        //1、加载配置文件

        //1.1 创建Properties对象
        Properties pro = new Properties();

        //1.2 加载配置文件,转换为一个集合

        //1.2.1获取class目录下的配置文件

        //创建类加载器
        ClassLoader classLoader = ReflectTest.class.getClassLoader();

        InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");
        pro.load(resourceAsStream);

        //2、获取配置文件中定义的数据
        String className = pro.getProperty("className");
        String methodName = pro.getProperty("methodName");

        //3、加载该类进内存
        Class cls = Class.forName(className);

        //4、创建对象
        Object obj = cls.newInstance();

        //5、获取方法
        Method method = cls.getmethod(methodName);

        //6、执行方法
        method.invoke(obj);

    }
}

In the future, more and more real scenes will need to use the soul technology of reflection. In short, take a good look and learn.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>