动态代理
来源:互联网 发布:ftp同步软件 知乎 编辑:程序博客网 时间:2024/06/05 07:49
1接口
public interface ArithmeticCaculator {
int add(int a, int b);int sub(int a, int b);
}
2.实现类
public class ArithmeticCaculatorImpl implements ArithmeticCaculator {
@Override
public int add(int a, int b) {
return a + b;
}
@Override
public int sub(int a, int b) {
return a - b;
}
}
3.代理类
public class AritmethticCaculatorProxy {
// 要代理的目标对象
ArithmeticCaculator target;
public AritmethticCaculatorProxy(ArithmeticCaculator target) {
this.target = target;
}
public ArithmeticCaculator proxy() {
ClassLoader loader = target.getClass().getClassLoader(); // 代理对象由哪个类加载器加载
Class<?>[] interfaces = target.getClass().getInterfaces(); // 代理对象所实现的接口
InvocationHandler invocationHandler = new InvocationHandler() {// 代理对象调用其中的方法时,執行該代碼
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before:" + Arrays.asList(args));
Object result = method.invoke(target, args);
System.out.println("result:" + result);
return result;
}
};
return (ArithmeticCaculator) Proxy.newProxyInstance(loader, interfaces, invocationHandler);
}
}
4.测试
public class ceshi {
public static void main(String[] args) throws Exception {
ArithmeticCaculator arithmeticCaculator =new ArithmeticCaculatorImpl();
AritmethticCaculatorProxy Proxy =new AritmethticCaculatorProxy(arithmeticCaculator );
ArithmeticCaculator target =Proxy.proxy();
target.add(1, 2);
}
}
- 代理-->静态代理&动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- 动态代理
- *** stack smashing detected ***与GCC “stack smashing detected”机制
- jquery.Callbacks的实现
- BT5 ip 参数永久修改
- maven打包可以行文件,包含依赖包等
- 代码中特殊的注释技术——TODO、FIXME和XXX的用处
- 动态代理
- 勒索病毒席卷全球并发生变种 国内多家企事业单位遭受攻击
- Spring中出现的he hierarchy of the type ** is inconsistent问题解决办法
- MVC5+EF6 入门完整教程五
- IOS开发之关键字synchronized(线程加锁)
- Zigbee音频, 6LowPAN, IEEE 802
- [Android 知识点剖析] Looper Handler MessageQueue
- 动态规划
- Spring @Transactional