setXxx_getXxx 2017-03-16 13:49 采纳率: 57.1%
浏览 963

动态代理对象有点看不懂,求解

package cn.itcast_06;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {

private Object target; // 目标对象

public MyInvocationHandler(Object obj) {
    this.target = obj;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    System.out.println("权限校验");
    Object result = method.invoke(target, args);
    System.out.println("日志举例");
    return result; // 返回的是代理对象
}

}

package cn.itcast_06;

import java.lang.reflect.Proxy;

public class Test {
public static void main(String[] args) {
UserDao ud = new UserDaoImpl();
ud.add();
ud.delete();
ud.update();
ud.find();
System.out.println("----------");
// 我们要创建一个动态代理对象
// Proxy类中有一个方法可以创建动态代理对象
// public static Object newProxyInstance(ClassLoader loader,Class<?>[]
// interfaces,InvocationHandler h)
// 我准备对ud对象做一个代理对象
MyInvocationHandler handler = new MyInvocationHandler(ud);
UserDao proxy = (UserDao) Proxy.newProxyInstance(ud.getClass()
.getClassLoader(), ud.getClass().getInterfaces(), handler);
proxy.add();
proxy.delete();
proxy.update();
proxy.find();
System.out.println("----------");

    StudentDao sd = new StudentDaoImpl();
    MyInvocationHandler handler2 = new MyInvocationHandler(sd);
    StudentDao proxy2 = (StudentDao) Proxy.newProxyInstance(sd.getClass().getClassLoader(),
            sd.getClass().getInterfaces(), handler2);
    proxy2.login();
    proxy2.regist();
}

}

  • 写回答

1条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)