Java basic reflection

foreword

Recently, I was reviewing the knowledge of the JavaSE part, recording some weak knowledge, learning methods, learning through videos and books, watching the video of Mr. Han Shunping's 30-day learning Java at station B, and reading the basic knowledge of Java core technology volume I in the book (original Book 10th Edition).

Han Shunping learned Java in 30 days Address: https://www.bilibili.com/video/BV1g84y1F7df?spm_id_from=333.999.0.0
insert image description here

An introduction to reflection

1. Bring out reflections

need
insert image description here

Code:

package com.dudu.demo1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Cat {
    
    
    private  String name;
    private int age;

    public void hi(){
    
    
        System.out.println("喵喵叫~~~");
    }

    public String getName() {
    
    
        return name;
    }

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

    public int getAge() {
    
    
        return age;
    }

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

class  Test{
    
    
    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    
    
        // 通过Cat.properties文件获取classfullpath和method的参数
        Properties properties =new Properties();
        properties.load(new FileInputStream("src\\Cat.properties"));
        String classfullpath = properties.getProperty("classfullpath");
        String method = properties.getProperty("method");
        System.out.println(classfullpath);
        System.out.println(method);

        // 获取到类路径
        Class cls = Class.forName(classfullpath);// 加载类对象
        Object o =cls.newInstance();// 加载实例
        Method method1 = cls.getMethod(method);// 获取实例方法
        method1.invoke(o);// 调用方式  方法.invoke(对象)
    }
}

Cat.properties (created in the src directory)

classfullpath=com.dudu.demo1.Cat
method=hi

analyze:

  • Using conventional means, it is impossible to directly convert a string-type class name (including path.class name) into an instance object, and correspondingly, the method under the instance object cannot be called. At this time, it can be realized by reflection technology.
  • The object is newInstance();obtained
  • In reflection, the method can also be regarded as an object ( Method), obtained through the class under getMethod(methodName);the .
  • In reflection, a method is called by 方法.invoke(对象).

2. Introduction to Reflection

insert image description here

3. Schematic diagram of Java reflection mechanism

insert image description here

  • Java reflection mechanism can be done

insert image description here

  • Main classes related to reflection

insert image description here
Practice Code:
Using Field and Constructor

  		// 获取属性
        Field field = cls.getField("publicData");
        System.out.println(field.get(o));

        // 获取构造方法
        Constructor constructor =cls.getConstructor();
        System.out.println(constructor);
        Constructor constructor2 =cls.getConstructor(String.class);
        System.out.println(constructor2);

Add the red box code to the Cat class:
insert image description here

running result:
insert image description here

  • Field objects represent member variables of a class
  • Under Class getField(属性名), you cannot get private properties, you need to blast it first.
  • Get properties in reflection:Field对象.get(实例对象)
  • Constructor object represents the constructor
  • The Constructor parameter with parameters is Class<?>type , and the specified constructor parameter type needs to pass in the corresponding parameter data type 数据类型.Class对象.

4. Reflection Advantages and Disadvantages

insert image description here
Code:

package com.dudu.demo1;

import java.lang.reflect.Method;

public class Test2 {
    
    

    public static void main(String[] args) throws Exception {
    
    
        // 方式一
        Cat cat = new Cat();
        // 开始计时
        long start = System.currentTimeMillis();
        for (int i=0;i<=100000000;i++){
    
    
            cat.hi();
        }

        long end = System.currentTimeMillis();
        System.out.println("耗时"+(end-start));

        // 方式二
        start = System.currentTimeMillis();
        Class cls = Class.forName("com.dudu.demo1.Cat");// 创建class
        Object o = cls.newInstance();// 获取对象
        Method hi = cls.getMethod("hi");// 获取方法对象
        // 调用方法
        for (int i=0;i<=100000000;i++){
    
    
            hi.invoke(o);
        }
         end = System.currentTimeMillis();
        System.out.println("耗时"+(end-start));

    }
}

Running effect (obviously it can be seen that calling the method through reflection is much less efficient):
insert image description here

5. Reflection call optimization - turn off access checking

insert image description here
As mentioned earlier, access to private properties requires blasting. The blasting here refers to closing access detection and calling getDeclaredXX to achieve blasting
insert image description here
( 访问私有属性时,会出现以下异常). The
insert image description here
modified code is as follows:
insert image description here
running effect ( 此时私有属性也可以访问):
insert image description here

2.Class class

  • Briefly

insert image description here

  • Common method

insert image description here

  • Get the Class class object

insert image description here
insert image description here
insert image description here

  • Which types have Class objects

insert image description here

3. Obtaining class structure information through reflection

  • java.lang.Class class

insert image description here

  • Field class

insert image description here

  • Method class

insert image description here

  • Constructor class

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42753193/article/details/124035780