当前位置:网站首页>[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
边栏推荐
- Vim 9.0正式发布!新版脚本执行速度最高提升100倍
- Concise analysis of redis source code 11 - Main IO threads and redis 6.0 multi IO threads
- SSL flood attack of DDoS attack
- 什么是调。调的故事
- 网络安全-破解系统密码
- Summary of interval knowledge
- 【数据挖掘】任务5:K-means/DBSCAN聚类:双层正方形
- Three core issues of concurrent programming - "deep understanding of high concurrent programming"
- Do not log in or log in to solve the problem that the Oracle database account is locked.
- 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
猜你喜欢
随机推荐
The difference between tail -f, tail -f and tail
7-25 read numbers (loop switch)
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
[untitled]
C#应用程序界面开发基础——窗体控制(4)——选择类控件
Leetcode skimming questions_ Sum of two numbers II - enter an ordered array
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
[shutter] animation animation (the core class of shutter animation | animation | curvedanimation | animationcontroller | tween)
MySQL - database query - basic query
网络安全-密码破解
leetcode刷题_两数之和 II - 输入有序数组
【数据挖掘】任务1:距离计算
SSL flood attack of DDoS attack
网络安全-DNS欺骗与钓鱼网站
LDC Build Shared Library
Concise analysis of redis source code 11 - Main IO threads and redis 6.0 multi IO threads
[error record] the shutter component reports an error (no directionality widget found. | richtext widgets require a directionality)
The meaning of wildcard, patsubst and notdir in makefile
openresty 缓存
![[技术发展-23]:DSP在未来融合网络中的应用](/img/2e/f39543a18a8f58b1d341ce72cc4427.png)







