Detailed reflection & usage scenarios

Reflection is the soul of frame design

(The prerequisite for use: the Class of the represented bytecode must be obtained first, and the Class class is used to represent the .class file (bytecode))

1. Overview of reflection

The JAVA reflection mechanism is in the running state, for any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; this dynamic information and dynamic call The function of the method of the object is called the reflection mechanism of the java language.

To dissect a class, you must first obtain the bytecode file object of the class. The dissection uses the methods in the Class class. So first, get the Class type object corresponding to each bytecode file.

The above summary is what is reflection

  • Reflection is to map various components in the java class into Java objects one by one

For example: A class has information such as member variables, methods, construction methods, packages, etc. A class can be dissected by using reflection technology, and each component is mapped into each object.

(Actually: these member methods and construction methods in a class have a class to describe in the added class)

The picture shows the normal loading process of the class: the principle of reflection is related to the class object.

Familiarize yourself with loading: the origin of the Class object is to read the class file into memory and create a Class object for it.

img

Among them, the Class object is very special. Let's first understand this Class class

2. View the API details of the Class class in java (1.7 API)

How to read the api in java for details, please refer to the basics of java - String string processing

img

ClassInstances of classes represent classes and interfaces in a running Java application. That is, there are more than N instances in the jvm, and each class has the Class object. (including primitive data types)

ClassThere is no public constructor. Objects are constructed automatically Classby the Java virtual machine when a class is loaded and by calling methods in the class loader . defineClassThat is, we don't need to handle the creation ourselves, the JVM has already created it for us.

There is no public construction method, and there are 64 methods, which are too many. Which one is used below will be explained in detail.

img

3. The use of reflection (the Student class is used here for demonstration)

First write a Student class.

1. Three ways to obtain Class objects

1.1 Object ——> getClass(); 1.2 Any data type (including basic data types) has a "static" class attribute 1.3 Through the static method of the Class class: forName (String className) (commonly used)

Among them, 1.1 is because of the getClass method in the Object class, because all classes inherit the Object class. Thus calling the Object class to obtain

img

package fanshe;
/**
 * 获取Class对象的三种方式
 * 1 Object ——> getClass();
 * 2 任何数据类型(包括基本数据类型)都有一个“静态”的class属性
 * 3 通过Class类的静态方法:forName(String  className)(常用)
 *
 */
public class Fanshe {
    
    
	public static void main(String[] args) {
    
    
		//第一种方式获取Class对象  
		Student stu1 = new Student();//这一new 产生一个Student对象,一个Class对象。
		Class stuClass = stu1.getClass();//获取Class对象
		System.out.println(stuClass.getName());
		
		//第二种方式获取Class对象
		Class stuClass2 = Student.class;
		System.out.println(stuClass == stuClass2);//判断第一种方式获取的Class对象和第二种方式获取的是否是同一个
		
		//第三种方式获取Class对象
		try {
    
    
			Class stuClass3 = Class.forName("fanshe.Student");//注意此字符串必须是真实路径,就是带包名的类路径,包名.类名
			System.out.println(stuClass3 == stuClass2);//判断三种方式是否获取的是同一个Class对象
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}
		
	}
}

Note: During runtime, only one Class object is generated for a class.

The third method is commonly used in the three ways, and what is the purpose of reflection when the first object is available. The second type of package that needs to import classes has too strong dependencies, and compilation errors will be thrown if the package is not imported. Generally, there is the third method. A string can be passed in or written in the configuration file and other methods.

2. Obtain the construction method through reflection and use:

student class:

package fanshe;
 
public class Student {
    
    
	
	//---------------构造方法-------------------
	//(默认的构造方法)
	Student(String str){
    
    
		System.out.println("(默认)的构造方法 s = " + str);
	}
	
	//无参构造方法
	public Student(){
    
    
		System.out.println("调用了公有、无参构造方法执行了。。。");
	}
	
	//有一个参数的构造方法
	public Student(char name){
    
    
		System.out.println("姓名:" + name);
	}
	
	//有多个参数的构造方法
	public Student(String name ,int age){
    
    
		System.out.println("姓名:"+name+"年龄:"+ age);//这的执行效率有问题,以后解决。
	}
	
	//受保护的构造方法
	protected Student(boolean n){
    
    
		System.out.println("受保护的构造方法 n = " + n);
	}
	
	//私有构造方法
	private Student(int age){
    
    
		System.out.println("私有的构造方法   年龄:"+ age);
	}
 
}

There are 6 construction methods in total;

Test class:

package fanshe;
 
import java.lang.reflect.Constructor;
 
 
/*
 * 通过Class对象可以获取某个类中的:构造方法、成员变量、成员方法;并访问成员;
 * 
 * 1.获取构造方法:
 * 		1).批量的方法:
 * 			public Constructor[] getConstructors():所有"公有的"构造方法
            public Constructor[] getDeclaredConstructors():获取所有的构造方法(包括私有、受保护、默认、公有)
     
 * 		2).获取单个的方法,并调用:
 * 			public Constructor getConstructor(Class... parameterTypes):获取单个的"公有的"构造方法:
 * 			public Constructor getDeclaredConstructor(Class... parameterTypes):获取"某个构造方法"可以是私有的,或受保护、默认、公有;
 * 		
 * 			调用构造方法:
 * 			Constructor-->newInstance(Object... initargs)
 */
public class Constructors {
    
    
 
	public static void main(String[] args) throws Exception {
    
    
		//1.加载Class对象
		Class clazz = Class.forName("fanshe.Student");
		
		
		//2.获取所有公有构造方法
		System.out.println("**********************所有公有构造方法*********************************");
		Constructor[] conArray = clazz.getConstructors();
		for(Constructor c : conArray){
    
    
			System.out.println(c);
		}
		
		
		System.out.println("************所有的构造方法(包括:私有、受保护、默认、公有)***************");
		conArray = clazz.getDeclaredConstructors();
		for(Constructor c : conArray){
    
    
			System.out.println(c);
		}
		
		System.out.println("*****************获取公有、无参的构造方法*******************************");
		Constructor con = clazz.getConstructor(null);
		//1>、因为是无参的构造方法所以类型是一个null,不写也可以:这里需要的是一个参数的类型,切记是类型
		//2>、返回的是描述这个无参构造函数的类对象。
	
		System.out.println("con = " + con);
		//调用构造方法
		Object obj = con.newInstance();
	//	System.out.println("obj = " + obj);
	//	Student stu = (Student)obj;
		
		System.out.println("******************获取私有构造方法,并调用*******************************");
		con = clazz.getDeclaredConstructor(char.class);
		System.out.println(con);
		//调用构造方法
		con.setAccessible(true);//暴力访问(忽略掉访问修饰符)
		obj = con.newInstance('男');
	}
	
}

Background output:

**********************所有公有构造方法*********************************
public fanshe.Student(java.lang.String,int)
public fanshe.Student(char)
public fanshe.Student()
************所有的构造方法(包括:私有、受保护、默认、公有)***************
private fanshe.Student(int)
protected fanshe.Student(boolean)
public fanshe.Student(java.lang.String,int)
public fanshe.Student(char)
public fanshe.Student()
fanshe.Student(java.lang.String)
*****************获取公有、无参的构造方法*******************************
con = public fanshe.Student()
调用了公有、无参构造方法执行了。。。
******************获取私有构造方法,并调用*******************************
public fanshe.Student(char)
姓名:男

Call method:

1. Obtain the construction method:

1). Batch method:
public Constructor[] getConstructors(): All "public" constructors
public Constructor[] getDeclaredConstructors(): Get all constructors (including private, protected, default, public)

2). Get a single method and call:
public Constructor getConstructor(Class... parameterTypes): get a single "public" constructor:
public Constructor getDeclaredConstructor(Class... parameterTypes): get "a certain constructor" can be private , or protected, default, public;

Call the constructor:

Constructor–>newInstance(Object… initargs)

2、

The explanation of api is:

newInstance(Object... initargs)
uses Constructorthe constructor represented by this object to create a new instance of the declared class of the constructor, and initializes the instance with the specified initialization parameters.

Its return value is of type T, so newInstance creates a new instance object of the declared class with a constructor. and call it for

3. Get member variables and call

student class:

package fanshe.field;
 
public class Student {
    
    
	public Student(){
    
    
		
	}
	//**********字段*************//
	public String name;
	protected int age;
	char sex;
	private String phoneNum;
	
	@Override
	public String toString() {
    
    
		return "Student [name=" + name + ", age=" + age + ", sex=" + sex
				+ ", phoneNum=" + phoneNum + "]";
	}
	
	
}

Test class:

package fanshe.field;
import java.lang.reflect.Field;
/*
 * 获取成员变量并调用:
 * 
 * 1.批量的
 * 		1).Field[] getFields():获取所有的"公有字段"
 * 		2).Field[] getDeclaredFields():获取所有字段,包括:私有、受保护、默认、公有;
 * 2.获取单个的:
 * 		1).public Field getField(String fieldName):获取某个"公有的"字段;
 * 		2).public Field getDeclaredField(String fieldName):获取某个字段(可以是私有的)
 * 
 * 	 设置字段的值:
 * 		Field --> public void set(Object obj,Object value):
 * 					参数说明:
 * 					1.obj:要设置的字段所在的对象;
 * 					2.value:要为字段设置的值;
 * 
 */
public class Fields {
    
    
 
		public static void main(String[] args) throws Exception {
    
    
			//1.获取Class对象
			Class stuClass = Class.forName("fanshe.field.Student");
			//2.获取字段
			System.out.println("************获取所有公有的字段********************");
			Field[] fieldArray = stuClass.getFields();
			for(Field f : fieldArray){
    
    
				System.out.println(f);
			}
			System.out.println("************获取所有的字段(包括私有、受保护、默认的)********************");
			fieldArray = stuClass.getDeclaredFields();
			for(Field f : fieldArray){
    
    
				System.out.println(f);
			}
			System.out.println("*************获取公有字段**并调用***********************************");
			Field f = stuClass.getField("name");
			System.out.println(f);
			//获取一个对象
			Object obj = stuClass.getConstructor().newInstance();//产生Student对象--》Student stu = new Student();
			//为字段设置值
			f.set(obj, "刘德华");//为Student对象中的name属性赋值--》stu.name = "刘德华"
			//验证
			Student stu = (Student)obj;
			System.out.println("验证姓名:" + stu.name);
			
			
			System.out.println("**************获取私有字段****并调用********************************");
			f = stuClass.getDeclaredField("phoneNum");
			System.out.println(f);
			f.setAccessible(true);//暴力反射,解除私有限定
			f.set(obj, "18888889999");
			System.out.println("验证电话:" + stu);
			
		}
	}

Background output:

************获取所有公有的字段********************
public java.lang.String fanshe.field.Student.name
************获取所有的字段(包括私有、受保护、默认的)********************
public java.lang.String fanshe.field.Student.name
protected int fanshe.field.Student.age
char fanshe.field.Student.sex
private java.lang.String fanshe.field.Student.phoneNum
*************获取公有字段**并调用***********************************
public java.lang.String fanshe.field.Student.name
验证姓名:刘德华
**************获取私有字段****并调用********************************
private java.lang.String fanshe.field.Student.phoneNum
验证电话:Student [name=刘德华, age=0, sex=

It can be seen from this

When calling the field: two parameters need to be passed:

Object obj = stuClass.getConstructor().newInstance();//Generate Student object – "Student stu = new Student(); //
Set value for field
f.set(obj, "Andy Lau");//For Student object The name attribute assignment in –”stu.name = “Andy Lau”

The first parameter: the object to be passed in, the second parameter: the actual parameter to be passed in

4. Get the member method and call it

student class:

package fanshe.method;
 
public class Student {
    
    
	//**************成员方法***************//
	public void show1(String s){
    
    
		System.out.println("调用了:公有的,String参数的show1(): s = " + s);
	}
	protected void show2(){
    
    
		System.out.println("调用了:受保护的,无参的show2()");
	}
	void show3(){
    
    
		System.out.println("调用了:默认的,无参的show3()");
	}
	private String show4(int age){
    
    
		System.out.println("调用了,私有的,并且有返回值的,int参数的show4(): age = " + age);
		return "abcd";
	}
}

Test class:

package fanshe.method;
 
import java.lang.reflect.Method;
 
/*
 * 获取成员方法并调用:
 * 
 * 1.批量的:
 * 		public Method[] getMethods():获取所有"公有方法";(包含了父类的方法也包含Object类)
 * 		public Method[] getDeclaredMethods():获取所有的成员方法,包括私有的(不包括继承的)
 * 2.获取单个的:
 * 		public Method getMethod(String name,Class<?>... parameterTypes):
 * 					参数:
 * 						name : 方法名;
 * 						Class ... : 形参的Class类型对象
 * 		public Method getDeclaredMethod(String name,Class<?>... parameterTypes)
 * 
 * 	 调用方法:
 * 		Method --> public Object invoke(Object obj,Object... args):
 * 					参数说明:
 * 					obj : 要调用方法的对象;
 * 					args:调用方式时所传递的实参;
):
 */
public class MethodClass {
    
    
 
	public static void main(String[] args) throws Exception {
    
    
		//1.获取Class对象
		Class stuClass = Class.forName("fanshe.method.Student");
		//2.获取所有公有方法
		System.out.println("***************获取所有的”公有“方法*******************");
		stuClass.getMethods();
		Method[] methodArray = stuClass.getMethods();
		for(Method m : methodArray){
    
    
			System.out.println(m);
		}
		System.out.println("***************获取所有的方法,包括私有的*******************");
		methodArray = stuClass.getDeclaredMethods();
		for(Method m : methodArray){
    
    
			System.out.println(m);
		}
		System.out.println("***************获取公有的show1()方法*******************");
		Method m = stuClass.getMethod("show1", String.class);
		System.out.println(m);
		//实例化一个Student对象
		Object obj = stuClass.getConstructor().newInstance();
		m.invoke(obj, "刘德华");
		
		System.out.println("***************获取私有的show4()方法******************");
		m = stuClass.getDeclaredMethod("show4", int.class);
		System.out.println(m);
		m.setAccessible(true);//解除私有限定
		Object result = m.invoke(obj, 20);//需要两个参数,一个是要调用的对象(获取有反射),一个是实参
		System.out.println("返回值:" + result);
		
		
	}
}

Console output:

***************获取所有的”公有“方法*******************
public void fanshe.method.Student.show1(java.lang.String)
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 final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
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()
***************获取所有的方法,包括私有的*******************
public void fanshe.method.Student.show1(java.lang.String)
private java.lang.String fanshe.method.Student.show4(int)
protected void fanshe.method.Student.show2()
void fanshe.method.Student.show3()
***************获取公有的show1()方法*******************
public void fanshe.method.Student.show1(java.lang.String)
调用了:公有的,String参数的show1(): s = 刘德华
***************获取私有的show4()方法******************
private java.lang.String fanshe.method.Student.show4(int)
调用了,私有的,并且有返回值的,int参数的show4(): age = 20
返回值:abcd

It can be seen from this:
m = stuClass.getDeclaredMethod(“show4”, int.class);//Invoke the designated method (all including private ones), you need to pass in two parameters, the first is the name of the method to be called, and the second It is the formal parameter type of the method, remember to be the type.
System.out.println(m);
m.setAccessible(true);//Release the private restriction
Object result = m.invoke(obj, 20);//Requires two parameters, one is the object to be invoked (obtained with reflection ), one is the actual parameter
System.out.println("return value: " + result);//

Console output:

***************获取所有的”公有“方法*******************
public void fanshe.method.Student.show1(java.lang.String)
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 final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
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()
***************获取所有的方法,包括私有的*******************
public void fanshe.method.Student.show1(java.lang.String)
private java.lang.String fanshe.method.Student.show4(int)
protected void fanshe.method.Student.show2()
void fanshe.method.Student.show3()
***************获取公有的show1()方法*******************
public void fanshe.method.Student.show1(java.lang.String)
调用了:公有的,String参数的show1(): s = 刘德华
***************获取私有的show4()方法******************
private java.lang.String fanshe.method.Student.show4(int)
调用了,私有的,并且有返回值的,int参数的show4(): age = 20
返回值:abcd

In fact, the member methods here: there is the word property in the model, that is, those setter() methods and getter() methods. There are also field components, which are explained in detail in introspection

5. Reflect the main method

student class:

package fanshe.main;
 
public class Student {
    
    
 
	public static void main(String[] args) {
    
    
		System.out.println("main方法执行了。。。");
	}
}

Test class:

package fanshe.main;
 
import java.lang.reflect.Method;
 
/**
 * 获取Student类的main方法、不要与当前的main方法搞混了
 */
public class Main {
    
    
	
	public static void main(String[] args) {
    
    
		try {
    
    
			//1、获取Student对象的字节码
			Class clazz = Class.forName("fanshe.main.Student");
			
			//2、获取main方法
			 Method methodMain = clazz.getMethod("main", String[].class);//第一个参数:方法名称,第二个参数:方法形参的类型,
			//3、调用main方法
			// methodMain.invoke(null, new String[]{"a","b","c"});
			 //第一个参数,对象类型,因为方法是static静态的,所以为null可以,第二个参数是String数组,这里要注意在jdk1.4时是数组,jdk1.5之后是可变参数
			 //这里拆的时候将  new String[]{"a","b","c"} 拆成3个对象。。。所以需要将它强转。
			 methodMain.invoke(null, (Object)new String[]{
    
    "a","b","c"});//方式一
			// methodMain.invoke(null, new Object[]{new String[]{"a","b","c"}});//方式二
			
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
		
		
	}
}

Console output:

The main method is executed. . .

6. Other uses of the reflection method - run the configuration file content through reflection

student class:

public class Student {
    
    
	public void show(){
    
    
		System.out.println("is show()");
	}
}

The configuration file takes a txt file as an example (pro.txt):

className = cn.fanshe.Student
methodName = show

Test class:

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;
 
/*
 * 我们利用反射和配置文件,可以使:应用程序更新时,对源码无需进行任何修改
 * 我们只需要将新类发送给客户端,并修改配置文件即可
 */
public class Demo {
    
    
	public static void main(String[] args) throws Exception {
    
    
		//通过反射获取Class对象
		Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"
		//2获取show()方法
		Method m = stuClass.getMethod(getValue("methodName"));//show
		//3.调用show()方法
		m.invoke(stuClass.getConstructor().newInstance());
		
	}
	
	//此方法接收一个key,在配置文件中获取相应的value
	public static String getValue(String key) throws IOException{
    
    
		Properties pro = new Properties();//获取配置文件的对象
		FileReader in = new FileReader("pro.txt");//获取输入流
		pro.load(in);//将流加载到配置文件对象中
		in.close();
		return pro.getProperty(key);//返回根据key获取的value值
	}
}

Console output:

is show()

Requirement:
When we upgrade this system, instead of the Student class, we need to write a new Student2 class, then we only need to change the content of the pro.txt file. The code does not need to be changed at all

The student2 class to replace:

public class Student2 {
    
    
	public void show2(){
    
    
		System.out.println("is show2()");
	}
}

The config file is changed to:

className = cn.fanshe.Student2
methodName = show2

Console output:

is show2();

7. Other uses of the reflection method - bypassing the generic check through reflection

Generics are used during compilation, and generics are erased (disappeared) after compilation. So it is possible to bypass the generic check through reflection

Test class:

import java.lang.reflect.Method;
import java.util.ArrayList;
 
/*
 * 通过反射越过泛型检查
 * 
 * 例如:有一个String泛型的集合,怎样能向这个集合中添加一个Integer类型的值?
 */
public class Demo {
    
    
	public static void main(String[] args) throws Exception{
    
    
		ArrayList<String> strList = new ArrayList<>();
		strList.add("aaa");
		strList.add("bbb");
		
	//	strList.add(100);
		//获取ArrayList的Class对象,反向的调用add()方法,添加数据
		Class listClass = strList.getClass(); //得到 strList 对象的字节码 对象
		//获取add()方法
		Method m = listClass.getMethod("add", Object.class);
		//调用add()方法
		m.invoke(strList, 100);
		
		//遍历集合
		for(Object obj : strList){
    
    
			System.out.println(obj);
		}
	}
}

Console output:

aaa
bbb
100

//This is the summary of reflection. The following introspection chapters are also related to reflection. It can be regarded as an advanced use of reflection. If you are interested, you can continue to view the introspection part of the summary.



Reflection usage scenarios

Java reflection technology is an advanced technology that allows programs to obtain class information at runtime, and can access and modify class properties and methods. Java reflection technology can be applied in many scenarios, such as:

  1. Framework design: In framework design, we usually need to use reflection technology to decouple, so that the framework can be extended and flexible.

  2. Unit testing: In unit testing, we can use reflection techniques to access private or protected class members to make testing more comprehensive.

  3. Dynamic proxy: use reflection technology to create a dynamic proxy object, so that any object that implements the interface can be represented at runtime, and functions such as AOP can be realized.

  4. JavaBean: JavaBean is a lightweight component that encapsulates the properties and methods of a JavaBean class and provides methods for accessing and modifying JavaBean properties. Reflection technology can access and modify the private properties and methods of JavaBean class.

  5. Serialization and deserialization: Many Java serialization and deserialization tools are implemented based on the Java reflection mechanism, such as Java's ObjectInputStream and ObjectOutputStream.

In short, Java reflection technology can be applied in many scenarios, especially in framework design and component development. Reflection technology can improve code flexibility and scalability, reduce code coupling, and simplify code writing. However, the reflection mechanism also increases the complexity of the program, so it must be used with caution.

Guess you like

Origin blog.csdn.net/qq_43842093/article/details/131755263