当前位置: 代码迷 >> 综合 >> JDK方式的动态代理
  详细解决方案

JDK方式的动态代理

热度:38   发布时间:2024-03-08 19:34:08.0

动态代理的步骤:

 1、创建动态处理器类,该类必须实现InvocationHandler接口,实现invoke方法;

 2、创建被代理的类和接口;

 3、通过Proxy类的静态方法newProxyInstance(ClassLoader loader,Class<?>[]interfaces,InvocationHandler h )方法                  创建代理对象;

4、通过代理对象调用方法。

/*** @Description: 测试动态代理*/
public class JdkProxy {@Testpublic 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);}
}

 

  相关解决方案