- --------------------------------------------------实现InvocationHandler接口------------------------------------
- package interceptor;
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.util.Date;
- public class LogInterceptor implements InvocationHandler{
- //被代理对象
- private Object target;
- //织入的代码
- private void beforMethod(Method method)
- {
- System.out.println(method.getName()+" start "+ new Date());
- }
- @Override
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- //先执行织入的代码
- beforMethod(method);
- //再执行被代理类里的方法
- method.invoke(target, args);
- return null;
- }
- //-------------getter setter-----------------------------------
- public Object getTarget() {
- return target;
- }
- public void setTarget(Object target) {
- this.target = target;
- }
- }
-----------------------------------------------------------dao--------------------------------------------------------------------------------
- package dao.impl;
- import dao.UserDao;
- import domain.User;
- public class UserDaoImpl implements UserDao {
- @Override
- public void save(User user) {
- System.out.println("start dao save");
- }
- }
---------------------------------------------------------test-----------------------------------------------------------------------------
- package test;
- import java.lang.reflect.Proxy;
- import interceptor.LogInterceptor;
- import dao.UserDao;
- import dao.impl.UserDaoImpl;
- import domain.User;
- public class ProxyTest {
- public static void main(String[] args) {
- //被代理对象
- UserDao userDao = new UserDaoImpl();
- //织入代码的类
- LogInterceptor li = new LogInterceptor();
- li.setTarget(userDao);
- //得到代理对象..注意这里的第一个参数 要和userDao是同一个类加载器
- //第二个参数是实现哪个接口,要和被代理实现同样的接口
- //第三个参数是织入的类,该类实现了InvocationHandle接口
- UserDao userDaoProxy = (UserDao)Proxy.newProxyInstance(userDao.getClass().getClassLoader(),
- new Class[]{UserDao.class}, li);
- userDaoProxy.save(new User());
- //代理类的名字
- System.out.println(userDaoProxy.getClass().getName());
- //其实主要实现是这样的
- /**
- * public class $proxy0 implements UserDao
- * {
- * public void save(User user)
- * {
- * //先得到要执行方法
- * Method m = getMethod();
- * //然后把自身传给 InvocationHandler的invoke方法
- * invoke(this,m,user);//public Object invoke(Object proxy, Method method, Object[] args)
- * }
- * }
- */
- }
- }
-----------------------------------------------------------------------------运行结果-------------------------------------
save start Sat Sep 10 21:39:13 CST 2011
start dao save
$Proxy0