0

我有A实现接口的类I。我有两个类BC每个类都扩展A并添加了一个新方法。Class 中的新方法BC. 我需要创建一个代理(某种复合),它应该具有 的所有方法和A中的新方法。BC

我试图在 CGLIB 中使用 Mixin$Generator 但我得到了 Error java.lang.ClassFormatError: Duplicate interface name in class file

有人可以提出解决方案吗?

4

1 回答 1

0

在 Java 中真正组合两个非接口类是不可能的。如果这两个对象具有共同的结构(by A),那么这将导致冲突,因为其中的任何字段或方法A都会加倍,这在 Java 中是非法的。但是,如果不存在这样的冲突信息,则这些类B不应C共享一个超类A

如果你想应用这种 mixin 委托,你需要为你的类创建一些接口抽象。然后可以在代理内部组合这些接口并委托给实例,B具体C取决于哪些实例实现了接口。这个,仅此而已,由 cglib 的Mixin. 以下是使用 cglib 进行组合如何工作的示例:

public interface Interface1 {
  String first();
}

public interface Interface2 {
  String second();
}

public class Class1 implements Interface1 {
  @Override
  public String first() {
    return "first";
  }
}

public class Class2 implements Interface2 {
  @Override
  public String second() {
    return "second";
  }
}

public interface MixinInterface extends Interface1, Interface2 { /* empty */ }

@Test
public void testMixin() throws Exception {
  Mixin mixin = Mixin.create(new Class[]{Interface1.class, Interface2.class,
      MixinInterface.class}, new Object[]{new Class1(), new Class2()});
  MixinInterface mixinDelegate = (MixinInterface) mixin;
  assertEquals("first", mixinDelegate.first());
  assertEquals("second", mixinDelegate.second());
}
于 2014-01-30T12:24:23.030 回答