当前位置:网站首页>[Appendix 6 Application of reflection] Application of reflection: dynamic agent
[Appendix 6 Application of reflection] Application of reflection: dynamic agent
2022-07-03 01:40:00 【Hard working little Naruto】
Write it at the front
Blog home page : Hard working Naruto
Series column :JavaSE Super detailed summary
Welcome friends , Like, focus on collection Learning together !
If there is a mistake , Please correct me !
about 【14 Chapter Java The reflex mechanism 】Java Reflection Development of
List of articles
One 、 summary
It refers to the method that the client calls other objects through the proxy class , And it is to create the proxy object of the target class dynamically when the program is running
- usage
● debugging
● Remote method call - Compared to static agents advantage :
In an abstract character ( Interface ) All declared methods are transferred to a centralized method of the calling processor for processing
relevant API
Proxy
: The operation class that specifically completes the agent , yes The parent of all dynamic proxy classes
Dynamically generate implementation classes for one or more interfaces through this class- To provide for Create dynamic proxy classes and dynamic proxy objects Of static state Method
●static Class<?> getProxyClass(ClassLoader loader, Class<?>… interfaces)
establish A dynamic proxy class corresponds to Class object
●static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,InvocationHandler h)
direct Create a dynamic proxy object
Two 、 principle
Use a proxy to wrap the object , Then replace the original object with the proxy object , Any call to the original object is made through a proxy . The proxy object determines whether and when method calls are transferred to the original object
Dynamic agent steps
- Create an implementation interface InvocationHandler Class , It has to be implemented invoke Method , To complete the specific operation of the agent
public Object invoke(Object theProxy, Method method, Object[] params) throws Throwable{
try{
Object retval = method.invoke(targetObj, params);
// Print out the result
System.out.println(retval);
return retval;
}catch (Exception exc){
}
}
- Create classes and interfaces that are proxied
- adopt Proxy Static method of
newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h)
Create a Subject The interface agent
RealSubject target = new RealSubject();
// Create a proxy to wrap the original implementation
DebugProxy proxy = new DebugProxy(target);
// Get a reference to the proxy through the Subject interface
Subject sub = (Subject) Proxy.newProxyInstance(
Subject.class.getClassLoader(),new Class[] {
Subject.class }, proxy);
- adopt Subject Proxy call RealSubject Methods to implement classes
String info = sub.say(“Peter", 24);
System.out.println(info);
3、 ... and 、 Dynamic proxy and AOP
AOP The proxy can replace the target object ,AOP The proxy contains all the methods of the target object
AOP The method in the proxy and the method of the target object exist differences :
AOP Methods within agents Before executing the target method 、 Then insert some general processing
Here is a more practical dynamic proxy mechanism :
Improve to
After improvement : Code segment 1、 Code segment 2、 Code segment 3 Separated from the dark code snippet , But the code snippet 1、2、3 And a specific method A Coupled ! The ideal effect is : Code block 1、2、3 Both methods can be executed A, There is no need to call the method of dark code directly in the way of hard coding in the program
public class DogUtil{
public void method1(){
System.out.println("===== General simulation method 1 =====");
}
public void method2(){
System.out.println("===== General simulation method 2 =====");
}
}
public class MyInvocationHandler implements InvocationHandler{
// Objects that need to be represented
private Object target;
public void setTarget(Object target){
this.target = target;}
// When executing all methods of a dynamic proxy object , Will be replaced by the following invoke Method
public Object invoke(Object proxy, Method method, Object[] args)
throws Exception{
DogUtil du = new DogUtil();
// perform DogUtil Object method1.
du.method1();
// With target Perform as a keynote method Method
Object result = method.invoke(target , args);
// perform DogUtil Object method2.
du.method2();
return result;}}
public class MyProxyFactory{
// For a given target Generate dynamic proxy objects
public static Object getProxy(Object target)
throws Exception{
// Create a MyInvokationHandler object
MyInvokationHandler handler =
new MyInvokationHandler();
// by MyInvokationHandler Set up target object
handler.setTarget(target);
// establish 、 And return a dynamic proxy object
return
Proxy.newProxyInstance(target.getClass().getClassLoader()
, target.getClass().getInterfaces() , handler);
}
}
public class Test{
public static void main(String[] args)
throws Exception{
// Create an original HuntingDog object , As target
Dog target = new HuntingDog();
// With designated target To create a dynamic proxy
Dog dog = (Dog)MyProxyFactory.getProxy(target);
dog.info();
dog.run();
}
}
Use Proxy When a dynamic proxy is generated , It's not always possible to create a dynamic proxy out of thin air
It is usually used to generate a dynamic proxy for a specified target object
summary : This dynamic agent needs careful consideration , I can't understand it. Keep reading
The author is a Java beginner , If there is any mistake in the article , Welcome to comment on private letter correction , Learning together ~~
If the article is useful to my friends , Like, focus on collection It's my biggest motivation !
Short step , A thousand miles , Book next time , Welcome, goodbye
边栏推荐
- 网络安全-密码破解
- GDB 在嵌入式中的相关概念
- 数学知识:能被整除的数—容斥原理
- Give you an array numbers that may have duplicate element values. It was originally an array arranged in ascending order, and it was rotated once according to the above situation. Please return the sm
- [机缘参悟-36]:鬼谷子-飞箝篇 - 面对捧杀与诱饵的防范之道
- [shutter] animation animation (animatedwidget animation use process | create animation controller | create animation | create animatedwidget animation component | animation operation)
- Tp6 fast installation uses mongodb to add, delete, modify and check
- Why can't the start method be called repeatedly? But the run method can?
- Why can't the start method be called repeatedly? But the run method can?
- [fh-gfsk] fh-gfsk signal analysis and blind demodulation research
猜你喜欢
mysql
[QT] encapsulation of custom controls
Give you an array numbers that may have duplicate element values. It was originally an array arranged in ascending order, and it was rotated once according to the above situation. Please return the sm
Why can't the start method be called repeatedly? But the run method can?
[principles of multithreading and high concurrency: 2. Solutions to cache consistency]
Virtual list
C#应用程序界面开发基础——窗体控制(3)——文件类控件
Learn the five skills you need to master in cloud computing application development
Smart management of Green Cities: Digital twin underground integrated pipe gallery platform
C application interface development foundation - form control (1) - form form
随机推荐
Types of map key and object key
[data mining] task 3: decision tree classification
网络安全-漏洞与木马
Qtablewidget lazy load remaining memory, no card!
leetcode刷题_两数之和 II - 输入有序数组
Soft exam information system project manager_ Real topic over the years_ Wrong question set in the second half of 2019_ Morning comprehensive knowledge question - Senior Information System Project Man
Work experience of a hard pressed programmer
What operations need attention in the spot gold investment market?
[shutter] animation animation (the core class of shutter animation | animation | curvedanimation | animationcontroller | tween)
[my advanced journey of OpenGL learning] collation of Euler angle, rotation order, rotation matrix, quaternion and other knowledge
Meituan dynamic thread pool practice ideas, open source
[机缘参悟-36]:鬼谷子-飞箝篇 - 面对捧杀与诱饵的防范之道
Thinkphp+redis realizes simple lottery
QTableWidget懒加载剩内存,不卡!
【数据挖掘】任务6:DBSCAN聚类
[North Asia data recovery] data recovery case of raid crash caused by hard disk disconnection during data synchronization of hot spare disk of RAID5 disk array
C language course information management system
网络安全-破解系统密码
LDC Build Shared Library
Test shift right: Elk practice of online quality monitoring