传统的代理模式是静态代理,也就是在方法区域中写入方法。
而动态代理的作用是,不修改实现类的代码,能够在代码的前后或者抛出异常的前后执行某个方法。
动态代理类的实现
//Interface public interface UserServiceInter { void save(); void delete(); void modify(); void search(); }
//entity public class UserService implements UserServiceInter{ public void save(){ System.out.println("保存"); } public void delete(){ System.out.println("删除"); } public void modify(){ System.out.println("修改"); } public void search(){ System.out.println("查询"); } }
//代理类以及测试类 import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class UserServiceProxyFactory implements InvocationHandler{ private UserService us; public UserServiceProxyFactory(UserService us) { this.us = us; } public UserServiceInter getUserServiceProxy(){ UserServiceInter us=(UserServiceInter) Proxy.newProxyInstance(UserService.class.getClassLoader(), UserService.class.getInterfaces() , this); return us; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before invoke"); Object invoke=method.invoke(us, args); System.out.println("after invoke"); return invoke; } public static void main(String[] args) { UserServiceProxyFactory factory=new UserServiceProxyFactory(new UserService()); UserServiceInter us=factory.getUserServiceProxy(); us.delete(); } }
运行结果:
注意:Proxy.newInsatance()的三个参数,第一个是实现类或者Interface的类加载器,第二个是实现类的Interface数组,第三个是Invocation接口的实现类
接收使用实现类的Interface接口进行接收。