动态代理的步骤:
1、创建动态处理器类,该类必须实现InvocationHandler接口,实现invoke方法;
2、创建被代理的类和接口;
3、通过Proxy类的静态方法newProxyInstance(ClassLoader loader,Class<?>[]interfaces,InvocationHandler h )方法 创建代理对象;
4、通过代理对象调用方法。
/**
* @Description: 测试动态代理
*/
public class JdkProxy {
@Test
public void test(){
//真实类的类加载器
ClassLoader classLoader = ProxyClass.class.getClassLoader();
//真实类实现的所有接口数组
Class<?>[] interfaces = ProxyClass.class.getInterfaces();
//自己编写的动态处理器
ProxyInvocationHandler handler = new ProxyInvocationHandler(new ProxyClass());
/*
newProxyInstance方法参数:
ClassLoader loader:真实类的类加载器
Class<?>[] interfaces: 真实类实现的所有接口数组
InvocationHandler h:自己编写的动态处理器
*/
ProxyInterface proxyInstance = (ProxyInterface)Proxy.newProxyInstance(
classLoader, interfaces, handler);
//动态调用方法
proxyInstance.say(",动态加强方法");
}
}
/**
* @Description: 动态管理器类
*/
class ProxyInvocationHandler implements InvocationHandler {
//维护目标接口
private ProxyInterface proxyInterface;
//通过构造器初始化目标接口,传入真实目标类对象
public ProxyInvocationHandler(ProxyInterface proxyInterface) {
this.proxyInterface = proxyInterface;
}
/**
* 实现动态代理方法,参数:
* Object Proxy:需要代理的类对象,一般是这个类中维护的目标对象
* Method method:需要代理的方法
* Object[] args:需要代理的方法的参数数组
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("前置操作");
System.out.println("method"+method);
System.out.println("args"+args);
/* 注意传参 */
Object result = method.invoke(proxyInterface, args);
System.out.println("后置操作");
return result;
}
}
/**
* @Description: 目标接口
*/
interface ProxyInterface {
public void say(String str);
}
/**
* @Description: 目标类
*/
class ProxyClass implements ProxyInterface{
public void say(String str) {
System.out.println("我是目标"+str);
}
}
本文介绍了使用JDK实现动态代理的四个关键步骤:创建实现InvocationHandler接口的动态处理器类,定义被代理的类和接口,通过Proxy的newProxyInstance方法生成代理对象,最后通过代理对象执行方法。
2765

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



