当前位置:网站首页>[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
边栏推荐
- Three core issues of concurrent programming - "deep understanding of high concurrent programming"
- Take you ten days to easily complete the go micro service series (I)
- [FPGA tutorial case 6] design and implementation of dual port RAM based on vivado core
- C#应用程序界面开发基础——窗体控制(1)——Form窗体
- uniapp组件-uni-notice-bar通告栏
- [Cao gongzatan] after working in goose factory for a year in 2021, some of my insights
- wirehark数据分析与取证A.pacapng
- Vant implements a simple login registration module and a personal user center
- Types of map key and object key
- Type expansion of non ts/js file modules
猜你喜欢
STM32 - vibration sensor control relay on
Virtual list
C application interface development foundation - form control (2) - MDI form
[FPGA tutorial case 6] design and implementation of dual port RAM based on vivado core
QTableWidget懒加载剩内存,不卡!
【数据挖掘】任务4:20Newsgroups聚类
Vant 实现简单的登录注册模块以及个人用户中心
Using tensorboard to visualize the model, data and training process
Arduino dy-sv17f automatic voice broadcast
Leetcode skimming questions_ Sum of two numbers II - enter an ordered array
随机推荐
LDC Build Shared Library
Summary of interval knowledge
tail -f 、tail -F、tailf的区别
Types of map key and object key
云原生题目整理(待更新)
网络安全-最简单的病毒
网络安全-钓鱼
[fh-gfsk] fh-gfsk signal analysis and blind demodulation research
【数据挖掘】任务6:DBSCAN聚类
The thread reuse problem of PageHelper using ThreadLocal, did you use it correctly?
网络安全-破解系统密码
[error record] the shutter component reports an error (no directionality widget found. | richtext widgets require a directionality)
数学知识:Nim游戏—博弈论
简易分析fgui依赖关系工具
[my advanced journey of OpenGL learning] collation of Euler angle, rotation order, rotation matrix, quaternion and other knowledge
Smart management of Green Cities: Digital twin underground integrated pipe gallery platform
Druid database connection pool
[data mining] task 2: mimic-iii data processing of medical database
[FPGA tutorial case 5] ROM design and Implementation Based on vivado core
Mathematical knowledge: Nim game game theory