当前位置:网站首页>[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
边栏推荐
- MySQL - database query - condition query
- Why is it not recommended to use BeanUtils in production?
- Three core issues of concurrent programming - "deep understanding of high concurrent programming"
- 简易分析fgui依赖关系工具
- 网络安全-中间人攻击
- C language course information management system
- Why can't the start method be called repeatedly? But the run method can?
- [shutter] animation animation (basic process of shutter animation | create animation controller | create animation | set value listener | set state listener | use animation values in layout | animatio
- SSL flood attack of DDoS attack
- 网络安全-破解系统密码
猜你喜欢

Wireshark data analysis and forensics a.pacapng

How is the mask effect achieved in the LPL ban/pick selection stage?

串口抓包/截断工具的安装及使用详解
![[shutter] animation animation (animatedbuilder animation use process | create animation controller | create animation | create components for animation | associate animation with components | animatio](/img/32/fa1263d9a2e5f77b0434fce1912cb2.gif)
[shutter] animation animation (animatedbuilder animation use process | create animation controller | create animation | create components for animation | associate animation with components | animatio
![[data mining] task 2: mimic-iii data processing of medical database](/img/ad/4e7b253d60b29351e3ef252ee5230f.png)
[data mining] task 2: mimic-iii data processing of medical database
![[my advanced journey of OpenGL learning] collation of Euler angle, rotation order, rotation matrix, quaternion and other knowledge](/img/ed/23331d939c9338760e426d368bfd5f.png)
[my advanced journey of OpenGL learning] collation of Euler angle, rotation order, rotation matrix, quaternion and other knowledge

【数据挖掘】任务4:20Newsgroups聚类

Androd gradle's substitution of its use module dependency

Virtual list

给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。【剑指Offer】
随机推荐
Wireshark data analysis and forensics a.pacapng
Force buckle 204 Count prime
After reading this article, I will teach you to play with the penetration test target vulnhub - drivetingblues-9
【QT】自定义控件的封装
數學知識:臺階-Nim遊戲—博弈論
网络安全-密码破解
View of MySQL
openresty 缓存
2022-02-15 reading the meta module inspiration of the influxdb cluster
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
测试右移:线上质量监控 ELK 实战
网络安全-动态路由协议RIP
Top ten regular spot trading platforms 2022
Thinkphp+redis realizes simple lottery
音程的知识的总结
[keil5 debugging] debug is stuck in reset_ Handler solution
leetcode刷题_两数之和 II - 输入有序数组
【面试题】1369- 什么时候不能使用箭头函数?
Types of map key and object key
String splicing function of MySQL