当前位置:网站首页>Dynamic agent explanation (July 16, 2020)
Dynamic agent explanation (July 16, 2020)
2022-07-07 23:17:00 【codepig16】
A dynamic proxy (2020.7.16)
characteristic : Create as you go , Load as you go
effect : Enhance the existing methods without modifying the source code
classification : Interface based dynamic proxy and subclass based dynamic proxy
First, let's introduce dynamic agents to a specific scenario , Suppose there is a computer manufacturer producer It wants to sell computers , So there's one Producer Classes and sale Method :
public class Producer {
public int sale(int money) {
System.out.println(" Sell a computer to make a profit " + money);
return money;
}
}
If the manufacturer sells a computer to the consumer , Then you can make profits :
public static void main(String[] args) {
Producer producer = new Producer();
producer.sale(1000);
}
But in real life , We all know that when we buy computers, we will not buy computers from computer manufacturers , It must be going to the mall , That is, the computer dealer goes to buy a computer , The requirement now is not to change the original manufacturer's code , We should divide computer profits , Is to enhance the method of selling computers , Here we need to use our dynamic proxy . Let users pay part of the money to computer manufacturers , Part to the dealer .
Here are two dynamic proxy methods and how they are implemented .
Proxy A dynamic proxy
It is Based on interfaces Dynamic proxy for , yes JDK Self contained , No additional jar package . It requires the proxy object to implement at least one interface , Otherwise, you cannot use this dynamic proxy .( Here we implement one Iproducer Interface , Defines a manufacturer's specification ).
* Dynamic agent based on Interface :
* Involved in the class :Proxy
* Provider :JDK official
* How to create a proxy object :
* Use Proxy Class newProxyInstance Method
* Requirements for creating proxy objects :
* The proxy class implements at least one interface , If not, you can't use
* newProxyInstance Method parameters :
* ClassLoader: Class loader
* It is used to load the bytecode of the proxy object . Use the same classloader as the proxied object . Fixed writing .
* Class[]: Bytecode array
* It is used to make the proxy object and the proxy object have the same method . Fixed writing .
* InvocationHandler: Used to provide enhanced code
* It's to let us write about how agents . We are generally implementation classes of this interface , Usually it's an anonymous inner class , But it's not necessary .
* The implementation classes of this interface are written by who .
It should be noted that the execution of each method of the proxied object will pass invoke Method , It acts as an interceptor , We are in invoke Method to enhance the original method . The meanings of the parameters are :
/
* effect : Any interface method that executes the proxied object passes through this method
* Meaning of method parameters
* @param proxy References to proxy objects
* @param method The current method of execution
* @param args Parameters required for the current execution method
* @return It has the same return value as the represented object method
* @throws Throwable
/*
Cooperate with the following code to better understand , stay main Function to simulate a consumer's consumption process :
public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
IProducer producer_proxy = (IProducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
int resultValue = 0;
int money = (int) args[0];
if (method.getName().equals("sale")) {
resultValue = (int) method.invoke(producer, money/2);
}
return resultValue;
}
});
producer_proxy.sale(500);
}
}
cglib A dynamic proxy
It is a dynamic proxy based on subclasses , When the proxied object does not implement an interface , also Not the final class When , You can use this dynamic proxy mode .
* Dynamic agent based on subclass :
* Involved in the class :Enhancer
* Provider : The third party cglib library
* How to create a proxy object :
* Use Enhancer Class create Method
* Requirements for creating proxy objects :
* The proxied class cannot be the final class
* create Method parameters :
* Class: Bytecode
* It is the bytecode used to specify the proxy object .
*
* Callback: Used to provide enhanced code
* It's to let us write about how agents . We are generally implementation classes of this interface , Usually it's an anonymous inner class , But it's not necessary .
* The implementation classes of this interface are written by who .
* We usually write the sub interface implementation class of this interface :MethodInterceptor
*/
Like interface based dynamic proxy inctercept Method is also an interceptor
```public class Client {
public static void main(String[] args) {
final Producer producer = new Producer();
IProducer producer_cglib = (IProducer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
int resultValue = 0;
int money = (int) objects[0];
if (method.getName().equals("sale")) {
resultValue = (int) method.invoke(producer, money/2);
}
return resultValue;
}
});
producer_cglib.sale(1000);
}
matters needing attention
- Dynamic proxy represents objects , For example, in the example above producer, What is enhanced is the method in the object
- Dynamic proxies are not useless , We often use dynamic agents to solve problems , In the thread pool close, Because when the thread pool is closed, the thread needs to return to the thread, not log off at the bottom , It can be realized by dynamic proxy .
- Spring Medium AOP Technology is implemented through dynamic agents , Greatly simplify the writing of code , Enhance the code without changing the code we write .
边栏推荐
- Adults have only one main job, but they have to pay a price. I was persuaded to step back by personnel, and I cried all night
- Advantages and disadvantages of rest ful API
- Network security CSRF
- OC variable parameter transfer
- Opencv scalar passes in three parameters, which can only be displayed in black, white and gray. Solve the problem
- Quelles sont les similitudes et les différences entre les communautés intelligentes et les villes intelligentes?
- PMP project management exam pass Formula-1
- PMP项目管理考试过关口诀-1
- Guessing game (read data from file)
- Unity3D学习笔记6——GPU实例化(1)
猜你喜欢

微信论坛交流小程序系统毕业设计毕设(8)毕业设计论文模板

微信论坛交流小程序系统毕业设计毕设(7)中期检查报告

Wechat forum exchange applet system graduation design completion (4) opening report

JMeter interface automated test read case, execute and write back result

14、 Two methods of database export and import

聊聊支付流程的设计与实现逻辑

微信论坛交流小程序系统毕业设计毕设(6)开题答辩PPT

Inftnews | web5 vs Web3: the future is a process, not a destination

Introduction to redis and jedis and redis things

leetcode-520. 检测大写字母-js
随机推荐
Inftnews | web5 vs Web3: the future is a process, not a destination
Wechat forum exchange applet system graduation design (3) background function
UE4_UE5蓝图command节点的使用(开启关闭屏幕响应-log-发布全屏显示)
Cases of agile innovation and transformation of consumer goods enterprises
微信论坛交流小程序系统毕业设计毕设(4)开题报告
Locate to the bottom [easy to understand]
Clean C disk
七月第一周
GEE(四):计算两个变量(影像)之间的相关性并绘制散点图
Grid
海内外技术人们“看”音视频技术的未来
Wechat forum exchange applet system graduation design completion (7) Interim inspection report
STL标准模板库(Standard Template Library)一周学习总结
力扣解法汇总648-单词替换
Brush question 4
FPGA基础篇目录
What are the similarities and differences between smart communities and smart cities
Statistical method for anomaly detection
Matlab-SEIR传染病模型预测
Introduction to redis and jedis and redis things