当前位置:网站首页>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);
}
}
边栏推荐
- leetcode两数相加go实现
- 数据库批量插入数据
- [opencv] image binarization
- 國產全中文-自動化測試軟件Apifox
- 7.1模拟赛总结
- Straighten elements (with transition animation)
- el-cascader回显只选中不显示的问题
- The El cascader echo only selects the questions that are not displayed
- Fabric. JS upload local image to canvas background
- The reason why sizeof (ARR) / sizeof (arr[0]) is used in the function to calculate the length of the array is incorrect
猜你喜欢
How matlab marks' a 'in the figure and how matlab marks points and solid points in the figure
Straighten elements (with transition animation)
Mysql基础---查询(1天学会mysql基础)
黑马笔记---Set系列集合
Gee dataset: chirps pentad high resolution global grid rainfall dataset
运维工作的“本手、妙手、俗手”
Gee: use of common mask functions in remote sensing image processing [updatemask]
Dark horse notes -- Set Series Collection
Nodejs (03) -- custom module
Gee series: Unit 3 raster remote sensing image band characteristics and rendering visualization
随机推荐
國產全中文-自動化測試軟件Apifox
Gee series: Unit 3 raster remote sensing image band characteristics and rendering visualization
Ubuntu 20.04 installing mysql8
Gee dataset: chirps pentad high resolution global grid rainfall dataset
Pycharm breakpoint management: temporarily cancel some breakpoints + run directly to a line
画波形图_数字IC
Draw a wave chart_ Digital IC
Splice characters in {{}}
Gee: remote sensing image composite and mosaic
Feign realizes file uploading and downloading
leetcode两数相加go实现
php/js cookie共享跨域的问题
CubeMx DMA笔记
Gee: use of common mask functions in remote sensing image processing [updatemask]
设置滚动条默认样式 谷歌浏览器
Gee series: Unit 2 explore datasets
JS interview collection test question 1
延时队列两种实现方式
Fabric.js IText 上标和下标
Fabric.js 右键菜单