简体   繁体   English

Java的动态代理如何实际工作?

[英]How does Java's Dynamic Proxy actually work?

I understand how to use Dynamic Proxies in Java but what I don't understand is how the VM actually creates a dynamic proxy. 我理解如何在Java中使用动态代理,但我不明白VM是如何实际创建动态代理的。 Does it generate bytecode and load it? 它会生成字节码并加载吗? Or something else? 或者是其他东西? Thanks. 谢谢。

至少对于Sun的实现,如果你看一下java.lang.reflect.Proxy的源代码,你会看到是的,它会动态生成字节代码(使用类sun.misc.ProxyGenerator )。

I suggest that you read Dynamic Proxy Classes : 我建议您阅读动态代理类

The Proxy.getProxyClass method returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. 在给定类加载器和接口数组的情况下,Proxy.getProxyClass方法返回代理类的java.lang.Class对象。 The proxy class will be defined in the specified class loader and will implement all of the supplied interfaces. 代理类将在指定的类加载器中定义,并将实现所有提供的接口。 If a proxy class for the same permutation of interfaces has already been defined in the class loader, then the existing proxy class will be returned; 如果已经在类加载器中定义了相同的接口排列的代理类,则将返回现有的代理类; otherwise, a proxy class for those interfaces will be generated dynamically and defined in the class loader. 否则,将动态生成这些接口的代理类,并在类加载器中定义。 [emphasis mine] [强调我的]

The proxy class is generated on-the fly (hence dynamic proxy) and loaded by the classloader. 代理类是在运行中生成 (因此是动态代理) 并由类加载器加载。 That's why if you debug applications that relies on JDK proxying you'll see bunch of classes named ' com.sun.proxy.$Proxy0 '. 这就是为什么如果你调试依赖于JDK代理的应用程序,你会看到一堆名为' com.sun.proxy。$ Proxy0 '的类。

To test my theory you can use an example from Dynamic proxy classes along with the VM parameter -verbose:class which will tell you the loaded classes by the classloader and you shall notice among the classes loaded the com.sun.proxy.$Proxy0 . 为了测试我的理论,您可以使用动态代理类中的示例以及VM参数-verbose:class ,它将告诉您类加载器加载的类,您应该注意加载com.sun.proxy。$ Proxy0的类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM