jdk动态代理使用:
核心方法:
使用java.lang.reflect.Proxy中的方法Proxy.newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h) 创建代理对象,三个参数分别为: 类加载器,实现的接口,额外功能;
废话不多说了,先来看一下JDK的动态是怎么用的。
测试准备:定义测试接口、测试接口实现类、额外功能
/**
* 定义测试接口
*/
public interface TestJDKAOP {
String getName(String name);
}
/**
* 测试接口实现类
*/
public class TestJDKAOPImplimplements TestJDKAOP {
@Override
public StringgetName(String name) {
System.out.println("getName======");
return name;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
*额外功能类
*/
public class TestInvokerimplements InvocationHandler {
private TestJDKAOPtestJDKAOP;
public TestInvoker(TestJDKAOP testJDKAOP) {
this.testJDKAOP = testJDKAOP;
}
@Override
public Objectinvoke(Object proxy, Method method, Object[] args)throws Throwable {
System.out.println("proxy before ==========");
Object invoke = method.invoke(testJDKAOP, args);
System.out.println("proxy after ===========");
return invoke;
}
}
测试类:
import java.lang.reflect.Proxy;
public class JDKAOPTest {
public static void main(String[] args){
//代理目标对象
TestJDKAOP testJDKAOP =new TestJDKAOPImpl();
//获取类加载器
ClassLoader classLoader = JDKAOPTest.class.getClassLoader();
//获取实现的接口
Class[] interfaces = testJDKAOP.getClass().getInterfaces();
//创建额外功能类
TestInvoker testInvoker =new TestInvoker(testJDKAOP);
//创建代理对象
TestJDKAOP testJDKAOPProxy = (TestJDKAOP)Proxy.newProxyInstance(
classLoader,
interfaces,
testInvoker);
String baozi = testJDKAOPProxy.getName("baozi");
System.out.println(baozi +"=========");
}
}
测试结果:
总结:其实这里基本上就是AOP的一个简单实现了,在目标对象的方法执行之前和执行之后进行了增强。JDK动态代理用起来是比较简单的,但是我们进一步思考:
1、代理对象是什么生成的呢?
2、InvocationHandler的invoke方法是什么调用的呢?
“知其然,知其所以然”