java 如何在java中创建代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4777050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:58:42  来源:igfitidea点击:

How to create proxy in java

javaproxy

提问by javaguy

How do they create proxy of a classin java. Do they create the proxy on as needed basis or they create it and have it around forever.

他们如何class在java中创建a的代理。他们是根据需要创建代理,还是创建并永久使用它。

回答by Bozho

You can create proxies in two basic ways:

您可以通过两种基本方式创建代理:

  • using the JDK mechanism, by interface. Take a look at java.lang.reflect.Proxy.
  • using some byte-code generation/manipulation library, on a concrete class. Take a look at cgliband javassist

Apache has a nice utility: commons-proxy. It wraps many mechanisms and frameworks for creating proxies.

Apache 有一个很好的实用程序:commons-proxy。它包装了许多用于创建代理的机制和框架。

This is all about dynamic proxies - i.e. those created at runtime. For static proxies - see wikipedia about the proxy pattern

这都是关于动态代理——即那些在运行时创建的。对于静态代理 - 请参阅有关代理模式的维基百科

Note that you are not making a proxy of a class - you are making a proxy of an object.

请注意,您不是在制作类的代理 - 您正在制作对象的代理。

回答by drekka

I agree with the comments that the question is a little vague. However, I'd suggest you look at some of the mocking frameworks such as easymock and mockito. Their source code is available and their core functionality is creating proxies of class and interfaces. So they are good concrete examples of how to go about creating proxies.

我同意这个问题有点含糊的评论。但是,我建议您查看一些模拟框架,例如 easymock 和 mockito。他们的源代码是可用的,他们的核心功能是创建类和接口的代理。所以它们是如何创建代理的很好的具体例子。