当前位置:网站首页>[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
边栏推荐
- Vant 实现简单的登录注册模块以及个人用户中心
- C#应用程序界面开发基础——窗体控制(3)——文件类控件
- Uniapp component -uni notice bar notice bar
- Create your first Kivy program Hello word (tutorial includes source code)
- Tp6 fast installation uses mongodb to add, delete, modify and check
- [技术发展-23]:DSP在未来融合网络中的应用
- Steps to obtain SSL certificate private key private key file
- Button wizard play strange learning - automatic return to the city route judgment
- 网络安全-信息收集
- GDB 在嵌入式中的相关概念
猜你喜欢
QTableWidget懒加载剩内存,不卡!
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
View of MySQL
Steps to obtain SSL certificate private key private key file
[QT] encapsulation of custom controls
[shutter] animation animation (animatedwidget animation use process | create animation controller | create animation | create animatedwidget animation component | animation operation)
Qtablewidget lazy load remaining memory, no card!
Everything文件搜索工具
C#应用程序界面开发基础——窗体控制(3)——文件类控件
Three core issues of concurrent programming - "deep understanding of high concurrent programming"
随机推荐
Vim 9.0正式发布!新版脚本执行速度最高提升100倍
[data mining] task 3: decision tree classification
Is there a handling charge for spot gold investment
Do not log in or log in to solve the problem that the Oracle database account is locked.
网络安全-动态路由协议RIP
C language course information management system
Mathematical knowledge: step Nim game game game theory
网络安全-信息收集
[shutter] animation animation (animatedbuilder animation use process | create animation controller | create animation | create components for animation | associate animation with components | animatio
给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。【剑指Offer】
网络安全-密码破解
Scheme and practice of cold and hot separation of massive data
串口抓包/截断工具的安装及使用详解
Three core issues of concurrent programming - "deep understanding of high concurrent programming"
一位苦逼程序员的找工作经历
Button wizard play strange learning - automatic return to the city route judgment
GDB 在嵌入式中的相关概念
Work experience of a hard pressed programmer
网络安全-防火墙
Smart management of Green Cities: Digital twin underground integrated pipe gallery platform