JDK动态代理和cglib代理

文章目录

  • 前言
  • 1.JDK动态代理
    • 1.1 定义一个接口
    • 1.2 实现接口
    • 1.3 自定义MyInvocationHandler去实现InvocationHandler接口
    • 1.4 测试jdk代理
    • 1.5 输出代理类
  • 2.cglib代理
    • 2.1 代理接口类
    • 2.2 代理普通类
    • 2.3 设置属性生成cglib代理类

前言

动态代理在平时的开发中用的也很多,统计接口调用耗时,日志功能,增强功能实现等。代理主要有两种 代理方式:
JDK动态代理特征

    1. 只能为接口创建代理对象
    1. 创建出来的代理都是java.lang.reflect.Proxy的子类

cglib代理
jdk动态代理只能代理接口类,cglib可以代理接口和普通类,通过子类来对被代理类实现增强扩展。

1.JDK动态代理

比如我们要统计某个方法的执行消耗的时间

1.1 定义一个接口

/**
 * 定义接口
 */
public interface IMyService {
    void method1();
}

1.2 实现接口

/**
 * 实现接口
 */
public class MyService implements IMyService {
    @Override
    public void method1() {
        System.out.println("method1 invokeed....");
    }
}

1.3 自定义MyInvocationHandler去实现InvocationHandler接口

/**
 * 自定义InvocationHandler
 */
public class MyInvocationHandler implements InvocationHandler {
    private Object target;
    //传入代理的目标类 
    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long startime = System.nanoTime();
        Object result = method.invoke(this.target, args); //将请求转发给target去处理
        long endTime = System.nanoTime();
        System.out.println(method + ",耗时(纳秒):" + ( endTime- startime));
        return result;
    }
}

1.4 测试jdk代理

public class TestProxy {
    public static void main(String[] args) {
        //1.创建被代理类
        IMyService service = new MyService();
        //2.自定义InvocationHandler
        MyInvocationHandler invocationHandler = new MyInvocationHandler(service);
        //3.利用Proxy创建代理对象
        Object proxyObject = Proxy.newProxyInstance(service.getClass().getClassLoader(), new Class[]{IMyService.class}, invocationHandler);
        //4.执行代理方法
        IMyService proxyService = (IMyService) proxyObject;
        //5.执行方法
        proxyService.method1();
    }
}

JDK动态代理和cglib代理_第1张图片

1.5 输出代理类

///加属性
//设置属性生成代理类
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");

再次执行方法会生成一个 代理类 :
JDK动态代理和cglib代理_第2张图片

public final class $Proxy0 extends Proxy implements IMyService {
    private static Method m1;
    private static Method m2;
    private static Method m3;
    private static Method m0;

    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void method1() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m3 = Class.forName("com.elite.javaee.service.IMyService").getMethod("method1");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

可以看到生成代理类 ,集成了Proxy并实现了代理的接口,代理类的方法有4个,其他的都是默认的方法,m3是代理生成的。

2.cglib代理

jdk代理需要的缺点是只能代理接口类,而cglib不一样 ,可以代理普通的类,是通过增强扩展实现,相当于创建一个被代理类的子类,能够重写父类方法,也是符合设计原则中的里式替换原则。

2.1 代理接口类

public class TestCglibProxy {
    public static void main(String[] args) {
        //1.创建一个enhancer类
        /**
         * Generates dynamic subclasses to enable method interception.
         * This class started as a substitute for the standard Dynamic Proxy support included with JDK 1.3,
         * but one that allowed the proxies to extend a concrete base class,
         * in addition to implementing interfaces. T
         * he dynamically generated subclasses override the non-final methods of the superclass and have hooks which callback to user-defined interceptor implementations.
         * The original and most general callback type is the MethodInterceptor, which in AOP terms enables "around advice"--that is, you can invoke custom code both before and after the invocation of the "super" method.
         * In addition you can modify the arguments before calling the super method, or not call it at all.
         * Although MethodInterceptor is generic enough to meet any interception need, it is often overkill.
         * For simplicity and performance, additional specialized callback types, such as LazyLoader are also available.
         * Often a single callback will be used per enhanced class, but you can control which callback is used on a per-method basis with a CallbackFilter.
         * The most common uses of this class are embodied in the static helper methods.
         * For advanced needs, such as customizing the ClassLoader to use, you should create a new instance of Enhancer.
         * Other classes within CGLIB follow a similar pattern.
         * All enhanced objects implement the Factory interface,
         * unless setUseFactory is used to explicitly disable this feature.
         * The Factory interface provides an API to change the callbacks of an existing object,
         * as well as a faster and easier way to create new instances of the same type.
         */
        Enhancer enhancer = new Enhancer();
        //2.设置代理的类
        enhancer.setInterfaces(new Class[]{IMyService.class});
       //2.通过设置callback来代理拦截的方法
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("cglib代理的方法==》"+method.getName());
                return null;
            }
        });
        IMyService proxyService = (IMyService) enhancer.create();
        proxyService.method1();

    }
}


2.2 代理普通类

其他代码都一致

 //设置代理的父类
enhancer.setSuperclass(Service.class);

Service service = (Service) enhancer.create();
service.method2();

2.3 设置属性生成cglib代理类

 //设置属性生成代理类
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "D:\\devproject\\devcode\\code\\SSMCollection\\com\\sun\\proxy");
      

可以看到生成的代理类去调用父类也就是被代理类的方法。
JDK动态代理和cglib代理_第3张图片

你可能感兴趣的:(Java,java,开发语言,代理模式)