用动态代理实现aop,$proxy0是代理类,A13是demo演示
$proxy0类代码:
package com.example.springdemo.A013; import com.example.springdemo.A013.A13.*; import java.lang.reflect.Method; public class $proxy0 implements A13.Foo{ private InvocationHandler h; public $proxy0(InvocationHandler h) { this.h = h; } @Override public void foo() throws Throwable { //功能增强和调用目标 h.invoke(this,foo, new Object[0]); } @Override public int bar() throws Throwable { Object result = h.invoke(this,bar, new Object[0]); return (int) result; } static Method foo; static Method bar; static { try { foo = Foo.class.getMethod("foo"); bar = Foo.class.getMethod("bar"); } catch (NoSuchMethodException e) { e.printStackTrace(); } } }
A13代码
package com.example.springdemo.A013; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class A13 { interface Foo{ void foo() throws Throwable; int bar() throws Throwable; } static class Target implements Foo{ @Override public void foo() { System.out.println("target foo"); } @Override public int bar(){ System.out.println("target bar"); return 100; } } interface InvocationHandler{ Object invoke(Object proxy,Method method, Object[] args) throws Throwable; } public static void main(String[] args) throws Throwable { //具体的handler实现 Foo proxy = new $proxy0(new InvocationHandler() { @Override public Object invoke(Object proxy,Method method, Object[] args) throws InvocationTargetException, IllegalAccessException { //功能增强 System.out.println("before..."); //调用目标 return method.invoke(new Target(),args); } }); proxy.foo(); int result = proxy.bar(); System.out.println(result); } }
这里其实用到了回调的思想,InvocationHandler是一个接口,在创建代理类的时候,初始化一个InvocationHandler,定义其增强的行为,然后对目标进行增强之后,调用目标的方法,调用目标的方法具有泛化性,所以用的是method.invoke(new Target(),args)。
当proxy.foo()执行的时候,会调用System.out.println("before..."),然后调用foo.invoke。foo = Foo.class.getMethod("foo");这行代码就是对proxy中的foo赋值,当proxy.foo()执行的时候,就知道要对目标的foo方法增强而不是对其他方法增强。