当前位置:网站首页>Basic knowledge of reflection (detailed explanation)
Basic knowledge of reflection (detailed explanation)
2022-07-03 04:57:00 【Day by day, the dish chicken Jie!!】
One : Export of reflection
1: problem
For example, we give a student class Its method show(), We write it into the configuration file ; Now we come to a new requirement, which is to change and rewrite one show() Method show()2, So how to modify without modifying the source code , At this time, we can complete through reflection
2: The process
student class :
public class Student {
public void show(){
System.out.println("is show()");
}
}
Profile to 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;
/* * We use reflection and configuration files , You can make : When the application is updated , There is no need to make any changes to the source code * We just need to send the new class to the client , And modify the configuration file */
public class Demo {
public static void main(String[] args) throws Exception {
// Get by reflection Class object
Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"
//2 obtain show() Method
Method m = stuClass.getMethod(getValue("methodName"));//show
//3. call show() Method
m.invoke(stuClass.newInstance());//stuClass.newInstance() Get the object of the current class
// before : object . Method (); Now? : Method name .( object )
}
// This method receives a key, Get the corresponding... In the configuration file value
public static String getValue(String key) throws IOException{
Properties pro = new Properties();// Get the object of the configuration file
FileReader in = new FileReader("pro.txt");// Get input stream
pro.load(in);// Load the stream into the profile object
in.close();
return pro.getProperty(key);// Return according to key Acquired value value
}
}
Console output :
is show()
demand :
When we upgrade this system , Don't Student class , And need to write a new Student2 Class time of , All you need to do is change pro.txt The content of the document can be . The code doesn't need to be changed at all
What to replace student2 class :
public class Student2 {
public void show2(){
System.out.println("is show2()");
}
}
The configuration file is changed to :
className = cn.fanshe.Student2
methodName = show2
Console output :
is show2();
3: summary
You can see that we just changed the configuration file , Without changing the source code
Two : What is reflex
JAVA The reflection mechanism is in the running state
For any class , Can know all the properties and methods of this class ;
For any object , Can call any of its methods and properties ;
The function of dynamically obtaining information and dynamically calling methods of objects is called java The reflexive mechanism of language
3、 ... and : The function of reflection
- At run time, determine the class that any object belongs to
- Construct an object of any class at run time
- Determine the member variables and methods of any class at run time
- Call the method of any object at run time
( To dissect a class , You must first get the bytecode file of this class (.class) object (class). And anatomy uses Class Methods in class . So first, get the corresponding Class Object of type .)
5、 ... and : About class Objects and class class
1:class object
Class The origin of the object is to class File read into memory , And create a Class object 
2:class class
- Represents a class , yes Java The origin and entrance of reflection mechanism
- Used to get all kinds of information about a class , Provides methods for obtaining class information
- Class Class inherits from Object class
- Class Class is the common drawing of all classes
- Each class has its own object , At the same time, each class is also regarded as an object , There are common drawings Class, Store class structure information , Be able to take out the corresponding Information about : The name of the class 、 attribute 、 Method 、 Construction method 、 Parents and interfaces .
- Class An instance of a class represents a running Java Classes and interfaces in applications . That is to say jvm There is N Multiple instances each class has its own Class object .( Including basic data types )
- Class There is no public construction method .Class Object is loaded by Java Virtual machine and by calling the defineClass Method is automatically constructed . That is to say, we don't need to deal with the creation by ourselves ,JVM It has been created for us . There is no public way to construct , Methods have in common 64 There are too many .

3: obtain class Object methods
adopt Class.forName(“ Full class name ”) ( The most common method )
try {
Class<?> perClazz = Class.forName("reflect_fanshe.Person");
System.out.println(perClazz);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
4: According to the reflection entry object (class) Get all kinds of information about the class
(1):perClazz.getMethods() Get all of the public Method ( Of the parent class , Implementation of the interface , Their own )
Class<?> perClazz = null;
try {
perClazz = Class.forName("reflect_fanshe.Person");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method[] methods = perClazz.getMethods();
// Traverse all methods
for (Method method : methods) {
System.out.println(method);
}
}
(2): Get the current class ( Only this kind of ) All methods and properties of , Including private

(3): Can get the object of the current class , And call class methods through objects

(4): Get instances of objects by reflection , And operating objects
class.newInstance() , And forced to type , Then you can manipulate the object , It's mainly about calling methods .
6、 ... and : The use of reflection
- java Know the specific information of class and object when coding , At this point, you can operate the class and object directly , No need to reflect
- If you don't know the specific information of the class or object when coding , At this point, reflection should be used to achieve
- For example, the name of the class is placed in XML In file , Attributes and attribute values are placed in XML In file , Need to read at run time XML file , Get the information of the class dynamically, and you can't know which classes the object or class may belong to at compile time , The program only relies on runtime information to discover the real information of the object and class
边栏推荐
- 1095 cars on campus (30 points)
- Use Sqlalchemy module to obtain the table name and field name of the existing table in the database
- ZABBIX monitoring of lamp architecture (2): ZABBIX basic operation
- [SQL injection point] location and judgment of the injection point
- Learning record of arouter principle
- Leetcode simple question: check whether the array is sorted and rotated
- 文献阅读_基于多模态数据语义融合的旅游在线评论有用性识别研究(中文文献)
- 1086 tree traversals again (25 points)
- Introduction to message queuing (MQ)
- [tools run SQL blind note]
猜你喜欢

论文阅读_中文NLP_ELECTRA

论文阅读_清华ERNIE

Oracle SQL table data loss

Introduction to message queuing (MQ)
![[tools run SQL blind note]](/img/c3/86db4568b221d2423914990a88eec2.png)
[tools run SQL blind note]

M1 Pro install redis

Leetcode simple question: check whether the string is an array prefix
![[Yu Yue education] basic reference materials of interchangeability and measurement technology of Zhongyuan Institute of Technology](/img/f1/d0dc4dc3fe49a2d2cd9e452a0ce31e.jpg)
[Yu Yue education] basic reference materials of interchangeability and measurement technology of Zhongyuan Institute of Technology

C language self-made Games: Sanzi (tic tac toe chess) intelligent chess supplement
![[luatos sensor] 2 air pressure bmp180](/img/88/2a6caa5fec95e54e3fb09c74ba8ae6.jpg)
[luatos sensor] 2 air pressure bmp180
随机推荐
Market status and development prospect prediction of global SoC Test Platform Industry in 2022
论文阅读_中文NLP_ELECTRA
Coordinatorlayout appbarrayout recyclerview item exposure buried point misalignment analysis
Hire cashier (differential constraint)
[luatos sensor] 2 air pressure bmp180
[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree
[XSS bypass - protection strategy] understand the protection strategy and better bypass
Interface frequency limit access
Network security textual research recommendation
Thesis reading_ Tsinghua Ernie
Problems encountered in fuzzy query of SQL statements
1118 birds in forest (25 points)
The current market situation and development prospect of the global gluten tolerance test kit industry in 2022
2022-02-11 daily clock in: problem fine brush
Shell script -- condition judgment
Shuttle + Alluxio 加速内存Shuffle起飞
联发科技2023届提前批IC笔试(题目)
Caijing 365 stock internal reference: what's the mystery behind the good father-in-law paying back 50 million?
Messy change of mouse style in win system
Blog building tool recommendation (text book delivery)