书单推荐:成为Java顶级程序员架构师 ,这20来本(高薪)必看点击获取
代理对象的生成方法是:
Proxy.newProxyInstance(...)
,进入这个方法内部,一步一步往下走会发现会调用
ProxyGenerator.generateProxyClass()
,这个方法用来生成代理类的字节码。
下面通过调用 ProxyGenerator.generateProxyClass()方法在本地生成代理类。
1.首先要有一个接口
2.生成代理类的方法如下
3.将生成的代理类导入到idea中查看是长这样
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // import com.example.springboottest.config.OrderService; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; protected static class $OrderService extends Proxy implements OrderService { private static Method m1; private static Method m3; private static Method m2; private static Method m0; public $OrderService(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 void query() throws { try { super.h.invoke(this, m3, (Object[])null); } catch (RuntimeException | Error var2) { throw var2; } catch (Throwable var3) { throw new UndeclaredThrowableException(var3); } } 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 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")); m3 = Class.forName("com.example.springboottest.config.OrderService").getMethod("query"); m2 = Class.forName("java.lang.Object").getMethod("toString"); m0 = Class.forName("java.lang.Object").getMethod("hashCode"); } catch (NoSuchMethodException var2) { throw new NoSuchMethodError(var2.getMessage()); } catch (ClassNotFoundException var3) { throw new NoClassDefFoundError(var3.getMessage()); } } }
可以发现在代理类中的构造方法中传入了我们实现的InvocationHandler,在调用方法时会回调invoke方法。
还可以发现代理类中继承了Proxy,由于java中是单继承的,所以java动态代理是针对接口的。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持谷谷点程序。
转载请注明:谷谷点程序 » jdk动态代理源码分析过程