标签:actor hand 切换 lib 因此 return 通知 切面 test
interface Person { void speak();}
实体类:
class Actor implements Person { private String content; public Actor(String content) { this.content = content;} public void speak(){ System.out.println(this.content); } }
代理类:
class Agent implements Person { private Actor actor; private String before; private String after; public Agent(Actor actor, String before, String after){ this.actor = actor; this.before = before; this.after = after; } public void speak(){ System.out.println("前置通知:" + this.before); this.actor.speak(); System.out.println("后置通知:" + this.after); } }
测试类:
public class StaticProxyTest{ public static void main(String[] args){ Actor actor = new Actor("实体类的真正内容"); Agent agent = new Agent(actor, "前置内容", "后置内容"); agent.speak(); } }
二、动态代理
1、JDK自带动态代理
public interface InvocationHandler{ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable; }
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException;
public interface Person{ public void show(); }
Actor实体类:
public class Actor implements Person{ public void show(){ System.out.println("真正实现的方法"); } }
Agent代理类:
public class DynamicAgent{ static class Agent implements InvocationHandler{ private Object proxy; public Agent(Object proxy){ this.proxy = proxy; } public Object invoke(Object object, Method method, Object[] args) throws Throwable { System.out.println("自己添加的前置通知"); //真正调用的方法 Object res = method.invoke(this.proxy, args); System.out.println("自己添加的后置通知"); return res; } public static Object agent(Class interfaceClazz, Object proxy){ return Proxy.newProxyInstance(interfaceClazz.getClassLoader(), new Class[]{interfaceClazz}, new Agent(proxy)); } } }
测试类ReflectTest:
public class ReflectTest{ public static void main(String[] args) throws InvocationTargetException, IllegralAccessException { Person person = (Person)DynamicAgent.agent(Person.class, new Actor()); person.show(); } }
这样以后对于不同的实现类来说,可以用同一个动态代理类来进行代理,但是这种方法有个缺点,就是被代理的类一定要是实现了某个接口的。
public class CglibAgent implements MethodInterceptor { private Object proxy; public Object getInstance(Object proxy){ this.proxy = proxy; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.proxy.getClass); enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object o, Method method, Object[] object, MethodProxy methodProxy) throws Throwable{ System.out.println("自己添加的前置通知"); Object res = methodProxy.invokeSuper(this.proxy, args); System.out.println("自己添加的后置通知"); return res; } //测试 public static void main(String[] args){ CglibAgent cglibAgent = new CglibAgent(); Actor actor = (Actor)cglibAgent.getInstance(new Actor()); actor.show(); } }
使用CGLIB处理之后,可以直接对实体类进行动态代理。
标签:actor hand 切换 lib 因此 return 通知 切面 test
原文地址:https://www.cnblogs.com/zzb-yp/p/12625277.html