虽然C#对Java语言中的委托和事件有语言支持,但我们必须要么使用匿名内部类进行绑定,要么使用反射代码http://oatv.com/pub/a/onjava/2003/05/21/delegates.html。在该页面的评论中,有一个关于CGLib多播代理的提示,但是谷歌代码似乎不知道任何用于该类的示例代码。有没有人有一个链接到一个工作的例子,或者有一个在他们的指尖?
发布于 2013-11-14 01:43:56
我知道这个问题很老了,但也许有一天有人也在想同样的问题。对于普通的C#-like委托,您可能会使用MethodDelegate,而不是MulticastDelegate。假设我们有一个简单的Java POJO bean:
public class SimpleBean {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}然后我们可以创建一个插装的(非反射的)委托,如下所示:
public static interface BeanDelegate {
String getValueFromDelegate();
}
@Test
public void testMethodDelegate() throws Exception {
SimpleBean bean = new SimpleBean();
bean.setValue("Hello world!");
BeanDelegate delegate = (BeanDelegate) MethodDelegate.create(
bean, "getValue", BeanDelegate.class);
assertEquals("Hello world!", delegate.getValueFromDelegate());
}关于此示例,有一些需要注意的事项:
MethodDelegate#create只接受一个方法名作为它的第二个参数。这是MethodDelegate将为您代理的方法。MethodDelegate实现了该接口,并可以转换为该接口。调用该方法时,它将对作为第一个参数的对象调用代理方法。有一些缺点/陷阱:
null),方法委托将无法工作。如果您的接口需要另一个返回类型(即使它更通用),您将得到一个IllegalArgumentException。(这很奇怪。)MulticastDelegate的工作方式略有不同。这一次,我们需要一个bean,它实际上实现了一个只有一个方法的接口:
public class SimpleMulticastBean implements DelegatationProvider {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public interface DelegatationProvider {
void setValue(String value);
}这一次,接口-在示例中名为DelegatationProvider -必须提供单个方法(与前面一样)。此接口必须由添加到此委托代理的任何对象来实现。这可以按如下方式完成:
@Test
public void testMulticastDelegate() throws Exception {
MulticastDelegate multicastDelegate = MulticastDelegate.create(
DelegatationProvider.class);
SimpleMulticastBean first = new SimpleMulticastBean();
SimpleMulticastBean second = new SimpleMulticastBean();
multicastDelegate = multicastDelegate.add(first);
multicastDelegate = multicastDelegate.add(second);
DelegatationProvider provider = (DelegatationProvider)multicastDelegate;
provider.setValue("Hello world!");
assertEquals("Hello world!", first.getValue());
assertEquals("Hello world!", second.getValue());
}同样,这个实现也有它的缺点:
进一步阅读的:我得到了灵感并总结了everything I know about cglib in a blog article。
https://stackoverflow.com/questions/4149991
复制相似问题