I have class A
that implements interface I
. I have two classes B
and C
, each extends A
and adds a new method. The new method in Class B
is different from that of C
. I need to create a Proxy (sort of composite) that should have all the methods of A
and the new methods in B
and C
.
I tried to use Mixin$Generator in CGLIB but I get Error java.lang.ClassFormatError: Duplicate interface name in class file
.
Can someone suggest a solution?
It is impossible to truly compose two non-interface classes in Java. If those two objects have a common structure (by A
), then this would result in a conflict since any field or method in A
would be doubled what is illegal in Java. However, if there is no such conflicting information present, then the classes B
and C
should not share a super class A
.
If you want to apply this sort of mixin delegation, you will need to create some interface abstraction for your classes. These interfaces can then be combined inside a proxy and delegate to the instances of B
and C
depending on which of those implement an interface. This, and nothing more, is offered by cglib's Mixin
. Here is an example of how the composition with cglib works:
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());
}