当前位置:网站首页>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
边栏推荐
- Handler understands the record
- Caijing 365 stock internal reference: what's the mystery behind the good father-in-law paying back 50 million?
- [set theory] relation properties (reflexivity | reflexivity theorem | reflexivity | reflexivity theorem | example)
- Realize file download through the tag of < a > and customize the file name
- 最大连续子段和(动态规划,递归,递推)
- M1 Pro install redis
- On typescript and grammar
- 论文阅读_清华ERNIE
- Review the configuration of vscode to develop golang
- 普通本科大学生活避坑指南
猜你喜欢
Source insight garbled code solution
联发科技2023届提前批IC笔试(题目)
5-36v input automatic voltage rise and fall PD fast charging scheme drawing 30W low-cost chip
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
[XSS bypass - protection strategy] understand the protection strategy and better bypass
Thesis reading_ Chinese medical model_ eHealth
Kept hot standby and haproxy
ZABBIX monitoring of lamp architecture (3): zabbix+mysql (to be continued)
Online VR model display - 3D visual display solution
JDBC database operation
随机推荐
Market status and development prospect prediction of the global fire hose industry in 2022
1103 integer factorization (30 points)
[tools run SQL blind note]
The 19th Zhejiang I. barbecue
Introduction to JVM principle
Current market situation and development prospect forecast of global UV sensitive resin 3D printer industry in 2022
论文阅读_ICD编码_MSMN
Review the configuration of vscode to develop golang
The programmer resigned and was sentenced to 10 months for deleting the code. JD came home and said that it took 30000 to restore the database. Netizen: This is really a revenge
[luatos sensor] 1 light sensing bh1750
【PHP漏洞-弱类型】基础知识、php弱相等、报错绕过
[clock 223] [binary tree] [leetcode high frequency]: 102 Sequence traversal of binary tree
1118 birds in forest (25 points)
Day 51 - tree problem
sql语句模糊查询遇到的问题
Valentine's day limited withdrawal guide: for one in 200 million of you
Why does I start with =1? How does this code work?
Caijing 365 stock internal reference: what's the mystery behind the good father-in-law paying back 50 million?
Uipath practice (08) - selector
Market status and development prospect forecast of global button dropper industry in 2022