Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, as java is a strongly-typed single inheritance language, you cannot escape the delegation.</p> <p>But you can avoid having to write a lot of delegation CODE, by using a dirty little trick with Proxies and reflection. Code follows</p> <pre><code>public interface Interface1 { void m1(); } public interface Interface2 { void m2(); } public class Class1 implements Interface1 { public void m1() { System.out.println(1); } } public class Class2 implements Interface2 { public void m2() { System.out.println(2); } } public interface MixinInterface extends Interface1, Interface2 { } </code></pre> <p>And this is how the magic happens</p> <pre><code>package j.with.pseudo.multiple.inheritance; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MixinBuilder { public static Object buildMixed(Class _interface, Object... impls){ InvocationHandler h = new MixinHandler(_interface.getInterfaces(), impls); return Proxy.newProxyInstance(MixinBuilder.class.getClassLoader(), new Class[]{_interface}, h); } public static void main(String[] args) { Class1 o1 = new Class1(); Class2 o2 = new Class2(); MixinInterface almost_like_multiple_inheritance_guy = (MixinInterface) buildMixed(MixinInterface.class, o1, o2); almost_like_multiple_inheritance_guy.m1(); almost_like_multiple_inheritance_guy.m2(); } private static class MixinHandler implements InvocationHandler{ private Class[] interfaces; private Object[] impls; public MixinHandler(Class[] interfaces, Object[] impls) { this.interfaces = interfaces; this.impls = impls; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { int i=0; for(Class _interface : interfaces){ if(method.getDeclaringClass().isAssignableFrom(_interface)){ return method.invoke(impls[i], args); } i++; } // TODO Auto-generated method stub throw new RuntimeException("Method not found: "+method); } } } </code></pre> <p>Pretty cool huh? :-)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload