动态代理
Aop 中,面向切面编程 就是基于动态代理来实现的
每一个动态代理的类都需要实现 InvocationHandler 接口
每一个代理类都管理到一个Handler. 通过代理对象调用一个方法时, 就会转发为由 InvocationHandler 接口中的 invoke 方法来调用。
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return null;
}
参数说明:
proxy : 生成的代理对象
method : 我们所要调用方法的Method对象
args : 该Mehod所需要的方法参数
Proxy 这个类提供了很多的方法 newProxyInstance 、getProxyClass、getInvocationHandler、getMethods 等,我们用的最多的是 newProxyInstance 该方法返回的是一个代理对象,委托给我们传入的InvocationHandler实例。
@return a new proxy object that delegates to the handler {@code h}
方法声明:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,
InvocationHandler invocationHandler)
throws IllegalArgumentException {
参数说明:
loader:类加载器类型,由哪个类加载器来加载代理对象
interfaces :一组接口,代理对象会实现该接口。
invocationHandler:当代理对象调用方法时,会关联到Handler 并调用该 invoke 方法。
Demo
定义一个接口
public interface PeopleInterface {
public void doSomething();
}
该接口实现
public class StudentImpl implements PeopleInterface {
@Override
public void doSomething() {
System.out.println("学习");
}
}
定义一个类实现 InvocationHandler
public class TestHandler implements InvocationHandler {
private PeopleInterface realObj;
public TestHandler(PeopleInterface realObj) {
this.realObj = realObj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理类: "+proxy.getClass().getName());
System.out.println("代理方法: "+method);
System.out.println("方法执行前");
method.invoke(realObj,args);
System.out.println("方法执行后");
return null;
}
}
proxy 为我们接口生成的代理类。
客户端代码
@Test
public void testProxy(){
StudentImpl people = new StudentImpl();
Class<?>[] interfaces = people.getClass().getInterfaces();
System.out.println("interface length : "+interfaces.length);
TestHandler helloProxy = new TestHandler(people);
PeopleInterface mPeopleProxy = (PeopleInterface) Proxy.newProxyInstance(helloProxy.getClass().getClassLoader(),interfaces, helloProxy);
mPeopleProxy.doSomething();
}
打印:
interface length : 1
代理类: com.sun.proxy.$Proxy4
代理方法: public abstract void com.test.mike.sourcelook.PeopleInterface.doSomething()
方法执行前
学习
方法执行后
注意: newProxyInstance 创建的代理对象是在 jvm 运行时动态生成的。不是我们的PeopleInterface 类型,命名是以$开头的
com.test.mike.sourcelook.PeopleInterface.doSomething()
说明我们在使用动态创建的 代理对象调用方法时,实际上是 委托给了与其关联的 TestHandler 对象。
参考资料:
http://www.cnblogs.com/xiaoluo501395377/p/3383130.html
动态代理与AOP

本文介绍了如何使用Java动态代理技术实现面向切面编程(AOP),包括定义接口、实现InvocationHandler接口以及通过Proxy类创建代理对象的过程。
1482

被折叠的 条评论
为什么被折叠?



