java动态代理

动态代理

动态代理是设计模式中的代理模式的一种,指为其他对象提供一种代理而能够访问控制该对象

其好处在于可以在不修改代码的情况下实现对原方法的扩展

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
interface App { void say(); }
class AppImpl implements App {
@Override
public void say() {
System.out.print("hello world");
}
}
class ProxyHandler implements InvocationHandler {
private Object proxied;
public ProxyHandler(Object proxied) { this.proxied = proxied; }
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(proxied,args);
}
}
public class Demo {
public static void main(String[] args) {
AppImpl app = new AppImpl();
App proxyApp = (App) Proxy.newProxyInstance(App.class.getClassLoader()
,new Class[]{App.class}
,new ProxyHandler(app));
proxyApp.say();
}
}
0%