package cn.edu.hpu.dao; import cn.edu.hpu.model.User; public interface UserDao { public void save(User u); }
package cn.edu.hpu.dao.Impl; import cn.edu.hpu.dao.UserDao; import cn.edu.hpu.model.User; public class UserDaoImpl implements UserDao{ public void save(User u) { System.out.println("add success!!"); } }
package cn.edu.hpu.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; //日志的拦截器 public class LogIntercept implements InvocationHandler{ private Object terget; public void beforeMethod(){ System.out.println("save start..."); } public void afterMethod(){ System.out.println("save end..."); } public void setTarget(Object terget) { this.terget=terget; } //无论调用代理对象的哪个方法,invoke方法都要被调用 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { beforeMethod(); m.invoke(terget, args); afterMethod(); return null; } }
@Test public void testProxy(){ //产生一个被代理的对象 UserDao userDao=new UserDaoImpl(); LogIntercept li=new LogIntercept(); li.setTarget(userDao); UserDao userDaoProxy=(UserDao)Proxy.newProxyInstance( userDao.getClass().getClassLoader(), new Class[]{UserDao.class}, li); userDaoProxy.save(new User()); }
UserDao userDaoProxy=(UserDao)Proxy.newProxyInstance( userDao.getClass().getClassLoader(), new Class[]{UserDao.class}, li);得到的是UserDao接口吗?测试一下:
顺便说一下,一般写程序推荐面向接口编程。
转载请注明出处:http://blog.csdn.net/acmman/article/details/44276427