当前位置:网站首页>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);
}
}
边栏推荐
- Gee: analyze the change of spatial centroid of remote sensing image [centroid acquisition analysis]
- Gee series: unit 9 generate sampling data in GEE [random sampling]
- Fabric.js 背景不受视口变换影响
- The El cascader echo only selects the questions that are not displayed
- Using QA band and bit mask in Google Earth engine
- Operator details
- Fabric. JS compact JSON
- Go implements leetcode rotation array
- Feign realizes file uploading and downloading
- Pyflink writes MySQL examples with JDBC
猜你喜欢
Gee data set: export the distribution and installed capacity of hydropower stations in the country to CSV table
Ls1046nfs mount file system
Fabric.js 渐变
LeetCode 241. Design priorities for operational expressions (divide and conquer / mnemonic recursion / dynamic programming)
【pyinstaller】_ get_ sysconfigdata_ name() missing 1 required positional argument: ‘check_ exists‘
Collectors.groupingBy 排序
Dark horse notes -- map set system
Dark horse notes -- Set Series Collection
7.TCP的十一种状态集
MySQL foundation --- query (learn MySQL foundation in 1 day)
随机推荐
Fabric.js 圆形笔刷
Gee series: unit 7 remote sensing image classification using GEE [random forest classification]
案例分享|智慧化的西部机场
Global and Chinese market of impact roll 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets of semiconductor laser therapeutics 2022-2028: Research Report on technology, participants, trends, market size and share
Paddlepaddle project source code
php/js cookie共享跨域的问题
Two implementation methods of delay queue
Collectors.groupingBy 排序
The El cascader echo only selects the questions that are not displayed
视差特效的原理和实现方法
Leetcode18题 【四数之和】递归解法
Domestic all Chinese automatic test software apifox
Gee data set: export the distribution and installed capacity of hydropower stations in the country to CSV table
Fabric.js IText 手动设置斜体
Basic differences between Oracle and MySQL (entry level)
Fabric.js 右键菜单
Set the default style of scroll bar Google browser
【pyinstaller】_ get_ sysconfigdata_ name() missing 1 required positional argument: ‘check_ exists‘
2022 Alibaba global mathematics competition, question 4, huhushengwei (blind box problem, truck problem) solution ideas