当前位置:网站首页>Reflection of the soul of the frame (important knowledge)
Reflection of the soul of the frame (important knowledge)
2022-07-02 05:19:00 【Share and summary】
List of articles
Preface
The concept of reflection was first developed by programming developers Smith stay 1982 in , Mainly refers to application access 、 testing 、 The ability to modify one's state and behavior . The proposal of this concept immediately attracted great attention from the programming community , Various research work is carried out , This led to a programming revolution , There are many object-oriented languages supporting reflection mechanism .
In the field of Computer Science , Reflection refers to a kind of application that can describe and control itself . stay Java In programming language , Reflection is a powerful tool , It is an implementation of abstract oriented programming , It makes code statements more flexible , Greatly improve the running ability of the code .
One 、 What is reflection ?
Java Reflection of (reflection) Mechanism means that in the running state of a program , You can construct an object of any class , You can know the class of any object , You can understand the member variables and methods of any class , You can call the properties and methods of any object . This function of dynamically obtaining program information and dynamically calling objects is called Java The reflexive mechanism of language . Reflection is seen as the key to dynamic language . After loading the class , In the method area of heap memory, a Class Object of type ( There is only one class Class object ), This object contains the complete class structure information . We can see the structure of the class through this object . This object is like a mirror , Look through this mirror to see the structure of the class , therefore , Our image is called : Reflection
Normal mode : Lead-in required ” Package class “ name → adopt new Instantiation → Get the instantiated object
Reflection mode : Instantiate objects → getClass() Method → Get complete ” Package class “ name
1.1 Do you understand the application scenario of reflection ?
For example, we usually write business code most of the time , It's rare to be exposed to scenes that directly use the reflection mechanism . however , That doesn't mean reflection doesn't work . contrary , It's because of the reflection , You can use all kinds of frameworks so easily . image Spring/Spring Boot、MyBatis And so on, the reflection mechanism is widely used in the framework . Dynamic proxies are also widely used in these frameworks , The implementation of dynamic proxy also depends on reflection . For example, the following is through JDK Implementation of dynamic proxy example code , The reflection class is used Method To call the specified method .
public class DebugInvocationHandler implements InvocationHandler {
/** * Real objects in proxy classes */
private final Object target;
public DebugInvocationHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws {
System.out.println("before method " + method.getName());
Object result = method.invoke(target, args);
System.out.println("after method " + method.getName());
return result;
}
}
in addition , image Java One of the most powerful weapons in the world annotation Reflection is also used in the implementation of . Why do you use Spring When , One @Component The annotation declares a class as Spring Bean Well ? Why do you go through a @Value The annotation is read to the value in the configuration file ? How does it work ? This is because you can analyze classes based on reflection , Then get the class / attribute / Method / Comments on the parameters of the method . After you get the annotation , We can do further processing .
Class.forName(“com.mysql.jdbc.Driver”) Reflection mechanism is also used .
1.2 Talk about the advantages and disadvantages of reflection mechanism ?
advantage : Can make our code more flexible 、 It provides convenience for various frameworks to provide out of the box functions
shortcoming : Let's have the ability to analyze operation classes at runtime , It also raises security issues . For example, there can be no
Depending on the security check of generic parameters ( The security check for generic parameters occurs at compile time ). in addition , The performance of reflection should also
Slightly worse , however , It doesn't really matter much to the framework .
Two 、 Reflect the actual combat
2.1 obtain Class Four ways of object
If we get this information dynamically , We need to rely on Class object .Class Class object will be a class's side
Law 、 Variables and other information tell the running program .Java There are four ways to get Class object :
1. If you know the specific class, you can use :
Class alunbarClass = TargetObject.class;
But we generally don't know the specific class , Basically, we get it by traversing the classes under the package Class object , through
Get Class Object is not initialized
2. adopt Class.forName() Get the path of the incoming class :
Class alunbarClass1 = Class.forName("cn.javaguide.TargetObject");
3. Through object instances instance.getClass() obtain :
TargetObject o = new TargetObject();
Class alunbarClass2 = o.getClass();
4. Through class loader xxxClassLoader.loadClass() Pass in the classpath to get :
Class clazz = ClassLoader.loadClass("cn.javaguide.TargetObject");
Get by class loader Class Object is not initialized , It means that some steps including initialization are not carried out
Abrupt , Static blocks and static objects are not executed
2.2 The basic operation of reflection
/** * @Author huang.bingXian * @Date 2021/4/27 * obtain Class How objects work */
public class GetClass {
public static void main(String[] args) throws ClassNotFoundException {
//1 Class.forName()
String classFullPath = "com.kuang.reflection.Cat";
Class<?> cla1 = Class.forName(classFullPath);
System.out.println(cla1);
//2 Class name .class It is used for parameter transfer
Class<Cat> cla2 = Cat.class;
System.out.println(cla2);
//3 Object name .getClass(); Use scenarios : Object with instance
Cat cat = new Cat();
Class cla3 = cat.getClass();
System.out.println(cla3);
System.out.println(cla1==cla2);
//4 Through class loader (4 Kind of )
//(1) Get the class loader first
ClassLoader classLoader = cat.getClass().getClassLoader();
//(2) Through class loader obtain Class object
Class<?> cla4 = classLoader.loadClass("com.kuang.reflection.Cat");
//cla1 cla2 cla3 cla4 It's actually the same object
//5 Is the basic data type obtained as follows Class object
Class<Integer> integerClass = int.class;
System.out.println(integerClass);
Class<Character> characterClass = char.class;
System.out.println(characterClass);
//6 The wrapper class corresponding to the basic data type can be through YYPE obtain Class object
Class<Integer> type = Integer.TYPE;
System.out.println(type);
}
}
2.3 Which types have Class object ?
/** * @Author huang.bingXian * @Date 2021/4/27 */
public class AllTypeClass {
public static void main(String[] args) {
Class<String> cla1 = String.class;
Class<Serializable> cla2 = Serializable.class;
Class<Integer[]> cla3 = Integer[].class;
Class<float[][]> cla4 = float[][].class;
Class<SuppressWarnings> cla5 = SuppressWarnings.class;
Class<Thread.State> cla6 = Thread.State.class;
Class<Long> cla7 = long.class;
Class<Void> cla8 = void.class;
Class<Class> cla9 = Class.class;
System.out.println(cla1);
System.out.println(cla2);
System.out.println(cla3);
System.out.println(cla4);
System.out.println(cla5);
System.out.println(cla6);
System.out.println(cla7);
System.out.println(cla8);
System.out.println(cla9);
}
}
边栏推荐
- Fabric.js 基础笔刷
- Principle and implementation of parallax effect
- Detailed explanation of Pointer use
- Basic differences between Oracle and MySQL (entry level)
- The reason why sizeof (ARR) / sizeof (arr[0]) is used in the function to calculate the length of the array is incorrect
- 创新永不止步——nVisual网络可视化平台针对Excel导入的创新历程
- Global and Chinese market of travel data recorder (VDR) 2022-2028: Research Report on technology, participants, trends, market size and share
- 【pyinstaller】_ get_ sysconfigdata_ name() missing 1 required positional argument: ‘check_ exists‘
- Oracle和MySQL的基本区别(入门级)
- Nodejs (03) -- custom module
猜你喜欢

Fabric. JS compact JSON

paddle: ValueError:quality setting only supported for ‘jpeg‘ compression

Creation and destruction of function stack frames

6. Network - Foundation
![Gee series: unit 10 creating a graphical user interface using Google Earth engine [GUI development]](/img/78/a17034d4b77d5c0dbe741f84a8ecd7.jpg)
Gee series: unit 10 creating a graphical user interface using Google Earth engine [GUI development]

Gee series: Unit 2 explore datasets

2022阿里巴巴全球数学竞赛 第4题 虎虎生威(盲盒问题、集卡问题)解决思路

Storage of data

Fabric.js IText 手动设置斜体

运维工作的“本手、妙手、俗手”
随机推荐
[opencv] image binarization
数据的储存
LeetCode 241. 为运算表达式设计优先级(分治/记忆化递归/动态规划)
國產全中文-自動化測試軟件Apifox
Dark horse notes -- Set Series Collection
Fabric.js 右键菜单
leetcode存在重复元素go实现
Online English teaching app open source platform (customized)
Fabric. JS basic brush
Global and Chinese market of cell culture freezers 2022-2028: Research Report on technology, participants, trends, market size and share
Domestic all Chinese automatic test software apifox
Leetcode 18 problem [sum of four numbers] recursive solution
Thread pool batch processing data
Collectors.groupingBy 排序
Feign realizes file uploading and downloading
Gee series: unit 9 generate sampling data in GEE [random sampling]
Using Kube bench and Kube hunter to evaluate the risk of kubernetes cluster
[quick view opencv] familiar with CV matrix operation with image splicing examples (3)
案例分享|智慧化的西部机场
C case of communication between server and client based on mqttnet