当前位置:网站首页>Detailed interpretation: the use of reflection
Detailed interpretation: the use of reflection
2022-07-20 22:11:00 【TheChainsmoker】
summary
Reflection is a mechanism , Using this mechanism, we can dissect the class and manipulate all the members of the class during the running process of the program ( Member variables , Member method , Construction method );
The premise of using reflection is to obtain this kind of bytecode file object , Namely Class object .
1、class Object
* The way 1: By class name .class get
* The way 2: By object name .getClass() Methods to get
* The way 3: adopt Class Class to get : static Class forName(" Class full name ")
Be careful : Of each class Class There's only one object .
Code example :
public class Demo01 {
public static void main(String[] args) throws ClassNotFoundException {
// get Girls Class Class object
Class c1 = Girls.class;
// Create a girl object
Girls g = new Girls();
// adopt getClass Method
Class c2 = g.getClass();
System.out.println(c1 == c2);
// adopt Class Class to get : static Class forName(" Class full name ")
Class c3 = Class.forName("com.girl.Girls");
System.out.println(c1 == c3);
System.out.println(c2 == c3);
}
}
class Common methods of objects :
* String getSimpleName(); Get the class name string : Class name
* String getName(); Get full class name : Package name + Class name
* T newInstance() ; Get an instance object
Code example :
public class Demo02 {
public static void main(String[] args) throws Exception {
// get Class object
Class c = Girls.class;
// Get the class name string : Class name
System.out.println(c.getSimpleName());
// Get full class name : Package name + Class name
System.out.println(c.getName());
// Create objects
Student stu = (Student) c.newInstance();
System.out.println(stu);
}
}
2、 Get the construction method through reflection
class Object gets the construction method
1. Constructor getConstructor(Class... parameterTypes)
* Get the corresponding... According to the parameter type Constructor object .
* You can only get public Modifies the constructor
2. Constructor getDeclaredConstructor(Class... parameterTypes)
* Get the corresponding... According to the parameter type Constructor object , Include private
3. Constructor[] getConstructors()
Get all constructor objects in the class , You can only get public Of
4. Constructor[] getDeclaredConstructors()
Get all constructor objects in the class , Include private Embellished
Common methods for constructing method objects :
1. T newInstance(Object... initargs)
Creates an object based on the specified parameters
2. void setAccessible(true)
Set whether to cancel permission check ,true Cancel permission check ( Violent reflex ),false Means not to cancel
Code example :
public class Demo03 {
@Test
public void test1() throws Exception {
// get Class object
Class c = Girls.class;
// Get two parameters to construct the method object
Constructor con = c.getDeclaredConstructor(String.class,String.class);
// Cancel permission check ( Violent reflex )
con.setAccessible(true);
// Create objects based on construction methods
Object obj = con.newInstance(" Zhang San "," Woman ");
System.out.println(obj);
}
@Test
public void test2() throws Exception {
// get Class object
Class c = Student.class;
// Get the parameterless constructor object
Constructor con = c.getConstructor();
// Create objects based on construction methods
Object obj = con.newInstance();
System.out.println(obj);
// Get the constructor object with parameters
Constructor con2 = c.getConstructor(String.class, String.class,int.class);
// Create objects The order of parameters is consistent with the order of attributes in the class
Object obj2 = con2.newInstance("jack", " male ",18);
System.out.println(obj2);
}
}
3、 Get member methods through reflection
Every member method is a Method Class object , therefore , When we get class Object time , Get by reflection method object , You can call the corresponding member method .
* Method getMethod(String name,Class...args);
* Obtain the corresponding construction method object according to the method name and parameter type , You can only get public Of
* Method getDeclaredMethod(String name,Class...args);
* Obtain the corresponding construction method object according to the method name and parameter type , Include private Of
* Method[] getMethods();
* Get all member method objects in the class , Returns an array of , You can only get public Decorated and containing a parent class
* Method[] getDeclaredMethods();
* Get all member method objects in the class , Returns an array of , Only get this kind of , contain private Embellished
method Common methods of objects :
* Object invoke(Object obj, Object... args)
* Call the specified object obj The method of
* args: Parameters passed when calling methods
* void setAccessible(true)
Set whether to cancel permission check ,true Cancel permission check ( Violent reflex ),false Means not to cancel
Code example
public class Demo04 {
// Reflection operation static method
@Test
public void test01() throws Exception {
// get Class object
Class c = Girls.class;
// Get the corresponding member method object according to the method name
Method method = c.getDeclaredMethod("work",String.class);
// adopt method Execute the corresponding method
method.invoke(null," Write code ");
}
/* * Method[] getMethods(); * Get all member method objects in the class , Returns an array of , You can only get public Decorated and containing a parent class * Method[] getDeclaredMethods(); * Get all member method objects in the class , Returns an array of , Only get this kind of , contain private Embellished */
@Test
public void test02() throws Exception {
// get Class object
Class c = Student.class;
// Get all member method objects in the class , Returns an array of , You can only get public Decorated and containing a parent class
// Method[] methods = c.getMethods();
// Get all member method objects in the class , Returns an array of , Only get this kind of , contain private Embellished
Method[] methods = c.getDeclaredMethods();
for (Method m: methods) {
System.out.println(m);
}
}
/* Method getDeclaredMethod(String name,Class...args); * Obtain the corresponding construction method object according to the method name and parameter type , */
@Test
public void test03() throws Exception {
// get Class object
Class c = Girls.class;
Girls girl = (Girls) c.newInstance();
// get sleep Method corresponding to Method object
Method m = c.getDeclaredMethod("sleep");
// Violent reflex
m.setAccessible(true);
m.invoke(girl);
}
@Test
public void test04() throws Exception {
// get Class object
Class c = Girls.class;
Girls girl = (Girls) c.newInstance();
Method m = c.getMethod("study");
// adopt m Object to perform stuy Method
m.invoke(girl);
/// get study Method corresponding to Method object
Method m2 = c.getMethod("study", int.class);
// adopt m2 Object to perform stuy Method
m2.invoke(girl,8);
}
}
4、 Reflection get member variable
The purpose of reflecting the operation of member variables
* adopt Field Object to assign and value the corresponding member variable
Field Class Overview
* Every member variable is a Field Class object .
class Object and Field Related methods
* Field getField(String name);
* Get the corresponding value according to the member variable name Field object , You can only get public modification
* Field getDeclaredField(String name);
* Get the corresponding value according to the member variable name Field object , contain private Embellished
* Field[] getFields();
* Get the corresponding values of all member variables Field object , You can only get public Of
* Field[] getDeclaredFields();
* Get the corresponding values of all member variables Field object , contain private Of
field Common methods of objects
void set(Object obj, Object value)
void setInt(Object obj, int i)
void setLong(Object obj, long l)
void setBoolean(Object obj, boolean z)
void setDouble(Object obj, double d)
Object get(Object obj)
int getInt(Object obj)
long getLong(Object obj)
boolean getBoolean(Object ob)
double getDouble(Object obj)
Code example :
public class Demo05 {
@Test
public void test01() throws Exception {
// get Class object
Class c = Girls.class;
// Get the corresponding values of all member variables Field object
// Field[] fields = c.getFields();
// Get the corresponding values of all member variables Field object , Include private
Field[] fields = c.getDeclaredFields();
for (Field f: fields) {
System.out.println(f);
}
}
@Test
public void test02() throws Exception {
// get Class object
Class c = Girls.class;
// Create objects
Object obj = c.newInstance();
// Get member variable name Corresponding Field object
Field f = c.getField("name");
// Give member variables name assignment
// Assign objects to obj Of name Attribute is assigned wisdom
f.set(obj," wisdom ");
System.out.println(f.get(obj)); // wisdom
// Get the name of the member variable
System.out.println(f.getName()); // name
// Give member variables gender assignment
// Get member variable gender Corresponding Field object
Field f1 = c.getDeclaredField("gender");
// Violent reflex
f1.setAccessible(true);
// Assign objects to obj Of gender Attribute assignment is male
f1.set(obj," male ");
System.out.println(obj);
}
}
5、 The effect of reflection
I talked so much about the use of reflection , that , What is the function of reflection ?
You can get all the components of a class at run time and then operate .
Can destroy encapsulation . You can also break the constraints of generics .
A more important use is suitable for : do Java Advanced framework , Basically, mainstream frameworks will design some general technical functions based on reflection .
such as :
Mybatis frame :
If you give any object data, I can directly help you parse the fields and save the corresponding data .
Student ( register , Store all the information fields )
Teacher ( register , Store all the information fields )
Manager ( register , Store all the information fields )
To make a long story short , Reflection is suitable for the bottom implementation of general technology framework , We often see the shadow of reflection in the underlying source code of the framework .
边栏推荐
- Hbuilderx eslint configuration
- JDBC quick start
- The most complete idea debug debugging skills in history (super detailed cases)
- 2022河南萌新联赛第(二)场:河南理工大学 G - 无限
- Dynamic memory management
- 20220718 helmet, pedestrian detection, data set
- 2022 Henan Mengxin League game 2: Henan University of technology L - HPU
- 2022河南萌新联赛第(二)场:河南理工大学 F - 手办
- 数据脱敏的功能与技术原理【详解】
- 相爱相杀大半年,马斯克和推特是怎么“分手”的?
猜你喜欢
Kubernetes 集群环境搭建
Ffmpeg video decoding
FFmpeg 音视频截取
对RPC的简单理解
2022 Henan Mengxin League game (2): Henan University of technology G - infinite
English语法_物主代词
【毕设教学】单片机控制步进电机
Session storage sessionstorage and local storage localstorage narrative and case analysis
[C# 调试]-使用 VS 2012 IDE 环境调试 C# 代码
2022 Henan Mengxin League game (2): Henan University of technology f - Handmade
随机推荐
Session storage sessionstorage and local storage localstorage narrative and case analysis
2022河南萌新联赛第(二)场:河南理工大学 A - 妙手
Google asked Indian taggers to tag reddit comment data sets, with an error rate of up to 30%?
数据仓库开发 SQL 使用技巧总结
nacos注册中心之服务地址的查询
FFmpeg 音视频截取
华为|MLGOPerf:用于优化性能的 ML 引导内联器
FFmpeg 视频解码
Simulate the implementation library function strcat-- append a copy of the source string to the target string (understand the memory overlap problem)
迅为STM32MP157开发板安装VMware Tool工具
火爆各平台的拼团功能,宝子们在多商户系统中玩过吗?
Improper use of BigDecimal caused P0 accident!
English sentence pattern reference exclusive Edition - object clause
Solution to the fourth weekly test of ACM intensive training of Hunan Institute of technology in 2022
可以DIY装修的商城系统,你也能拥有!
模拟实现库函数strcat--将源字符串的副本追加到目标字符串(理解内存重叠问题)
Dynamic memory management
Microservice testing
PMP practice once a day | don't get lost in the exam -7.19
CLion编译和使用动态库