当前位置:网站首页>动态代理的实现原理
动态代理的实现原理
2022-06-29 22:46:00 【不败顽童博主】
动态代理
动态代理来源于设计模式中的代理模式,在这里“动态”的意思作者将其理解为更加灵活多变,在动态代理类中定义一个接口作(InvocationHandler)为成员变量,并且调用接口定义的方法(invoke),接口定义的方法(invoke)并不实现它,而是让这个接口的实现类(此处使用lambda表达式实现)来实现它。因此可以达到动态的效果。
Foo接口
interface Foo{
void foo();
void bar();
}
Foo接口的实现类Target
class Target implements Foo{
@Override
public void foo() {
System.out.println("foo()");
}
@Override
public void bar() {
System.out.println("bar()");
}
}
代理接口
// 代理接口
interface InvocationHandler{
void invoke(Method method,Object[] objects) throws Throwable;
}
代理类
public class $Proxy0 implements Foo {
/** * 使用InvocationHandler接口,将需要代理的方法的实现部分转移到其子类实现, * 而在代理类中只需要定一个接口,并在需要代理的方法中调用invoke方法即可。 */
private InvocationHandler h;
public $Proxy0(InvocationHandler h) {
this.h = h;
}
@Override
public void foo() {
try {
Method foo = Foo.class.getDeclaredMethod("foo");
h.invoke(foo,new Object[0]);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
@Override
public void bar() {
try {
Method bar = Foo.class.getDeclaredMethod("bar");
h.invoke(bar,new Object[0]);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
main方法类
public class Main{
public static void main(String[] args) {
$Proxy0 proxy = new $Proxy0(new InvocationHandler() {
@Override
public void invoke(Method method, Object[] objects) throws Throwable {
// 1、功能增强
System.out.println("before....");
// 2、原始方法
Object result = method.invoke(new Target(), objects);
}
});
proxy.foo();
proxy.bar();
}
}
边栏推荐
- MySQL 锁常见知识点&面试题总结
- 从零实现深度学习框架——RNN从理论到实战【实战】
- Basic use of Nacos configuration center
- The third day
- Mysql database: read write separation
- Steady! The best posture for thousands of microservices to access Zadig (helm chart)
- Static keyword continuation, inheritance, rewrite, polymorphism
- Intranet penetration (NC)
- Number theory - division and blocking
- 服务器快速搭建AList集成网盘网站【宝塔面板一键部署AList】
猜你喜欢
随机推荐
正如以往我们对于互联网的看法一样,我们对于互联网的认识开始变得深度
Mysql database: partition
Design of Distributed Message Oriented Middleware
从零实现深度学习框架——LSTM从理论到实战【理论】
Nacos-配置中心基本使用
The development of grpc
Golang code specification sorting
static关键字续、继承、重写、多态
论文阅读《Large-Scale Direct SLAM with Stereo Cameras》
5-1 system vulnerability scanning
Node data collection and remote flooding transmission of label information
Gnawing down the big bone - sorting (I)
触摸按键与按键控制对应的LED状态翻转
SYSTEMd debugging
Welcome the "top ten" of the Municipal Association for science and technology • pay tribute to Lu Yi, a scientific and technological worker: an explorer guarding the transmission security of the power
Code sharing for making and developing small programs on the dating platform
Phpspreadsheet reading and writing Excel files
从零实现深度学习框架——RNN从理论到实战【实战】
Hematemesis finishing: a rare map of architects!
The client can connect to remote MySQL









