当前位置:网站首页>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
边栏推荐
- Esp32-c3 learning and testing WiFi (II. Wi Fi distribution - smart_config mode and BlueIf mode)
- Analysis of proxy usage of ES6 new feature
- Number of 1 in binary (simple difficulty)
- Market status and development prospect prediction of the global fire alarm sensor industry in 2022
- Number of uniform strings of leetcode simple problem
- [XSS bypass - protection strategy] understand the protection strategy and better bypass
- Market status and development prospect prediction of the global autonomous hybrid underwater glider industry in 2022
- Market status and development prospect prediction of global colorimetric cup cover industry in 2022
- Do you know UVs in modeling?
- 【PHP漏洞-弱类型】基础知识、php弱相等、报错绕过
猜你喜欢
![[USACO 2009 Dec S]Music Notes](/img/e6/282a8820becdd24d63dcff1b81fcaf.jpg)
[USACO 2009 Dec S]Music Notes

Online VR model display - 3D visual display solution

M1 Pro install redis

ZABBIX monitoring of lamp architecture (2): ZABBIX basic operation
![[luatos sensor] 1 light sensing bh1750](/img/70/07f29e072c0b8630f92ec837fc12d5.jpg)
[luatos sensor] 1 light sensing bh1750

Thesis reading_ ICD code_ MSMN

The consumption of Internet of things users is only 76 cents, and the price has become the biggest obstacle to the promotion of 5g industrial interconnection

Esp32-c3 learning and testing WiFi (II. Wi Fi distribution - smart_config mode and BlueIf mode)

Keepalived热备与HAProxy

并发操作-内存交互操作
随机推荐
The usage of micro service project swagger aggregation document shows all micro service addresses in the form of swagger grouping
Notes | numpy-07 Slice and index
Day 51 - tree problem
50 practical applications of R language (36) - data visualization from basic to advanced
Market status and development prospect prediction of the near infrared sensor industry of the global Internet of things in 2022
最大连续子段和(动态规划,递归,递推)
编译GCC遇到的“pthread.h” not found问题
MC Layer Target
"Niuke brush Verilog" part II Verilog advanced challenge
[set theory] relational representation (relational matrix | examples of relational matrix | properties of relational matrix | operations of relational matrix | relational graph | examples of relationa
Thesis reading_ Chinese NLP_ ELECTRA
论文阅读_中文医疗模型_ eHealth
Problems encountered in fuzzy query of SQL statements
Number of 1 in binary (simple difficulty)
MPM model and ab pressure test
Introduction to JVM principle
Wechat applet distance and map
[research materials] 2022q1 game preferred casual game distribution circular - Download attached
Uipath practice (08) - selector
[luatos sensor] 1 light sensing bh1750