动态代理理解
-
- public interface XiangQinInterface {
-
- public void xiangQin();
- }
-
- public class ZhangSanXiangQinInterfaceImpl implements XiangQinInterface {
- public void xiangQin() {
- System.out.println("张三去相亲,娶个漂亮老婆。");
- }
- }
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
-
-
- public class ReadyInvocationHandler implements InvocationHandler {
- //相亲接口的实现类,也就是张三相亲类
- private Object zhangSan = null;
-
- public ReadyInvocationHandler(Object realSubject) {
- this.zhangSan = realSubject;
- }
-
- public Object invoke(Object proxy, Method m, Object[] args) {
- Object result = null;
- try {
-
-
- System.out.println(proxy.getClass().getSimpleName());
- System.out.println("张三相亲前,代理人给他打扮了打扮。");
- result = m.invoke(zhangSan, args);
- } catch (Exception ex) {
- System.exit(1);
- }
- return result;
- }
- }
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
-
- public class HunJieSuo {
- public static void main(String args[]) {
- //先将张三相亲这个相亲的实现类实例化,也就是获得XiangQinInterface接口的一个实例对象
- XiangQinInterface zhangSan = new ZhangSanXiangQinInterfaceImpl();
-
-
- XiangQinInterface proxy = (XiangQinInterface) Proxy.newProxyInstance(
- zhangSan.getClass().getClassLoader(),
- zhangSan.getClass().getInterfaces(),
- new ReadyInvocationHandler(zhangSan));
- proxy.xiangQin();
-
- }
- }
欢迎关注本站公众号,获取更多信息