You might be able to use a Proxy instance for this. See this question for Proxy information (specifically, the second part of the answer.)
InvocationHandler you are writing will check to see which interface is used to invoke the method and delegate the corresponding method inside your object. Here's what your implementation looks like:
public class MyClass {
Then your InvocationHandler:
public class MyClassInvocationHandler implements InvocationHandler { private MyClass target; public MyClassInvocationHandler(MyClass target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (method.getDeclaringClass().equals(InterfaceA.class)) return MyClass.getMethod("doSomethingForA").invoke(target, args); else if (method.getDeclaringClass().equals(InterfaceB.class)) return MyClass.getMethod("doSomethingForB").invoke(target, args); else throw new UnsupportedOperationException("Unsupported interface: " + method.getDeclaringClass()); } catch (NoSuchMethodException ex) { throw new UnsupportedOperationException("Method not found", ex); } catch (IllegalAccessException ex) { throw new UnsupportedOperationException("Method was not public", ex); } catch (InvocationTargetException ex) {
Then, to create a proxy, you will go to both interfaces:
Proxy.newProxyInstance(null, new Class<?>[] { InterfaceA.class, InterfaceB.class }, new MyClassInvocationHandler(mc));
I think it will work. When you call it using one interface or another:
MyClass mc = new MyClass(); Object proxy = Proxy.newProxyInstance(null, new Class<?>[] { InterfaceA.class, InterfaceB.class }, new MyClassInvocationHandler(mc)); InterfaceA a = (InterfaceA) proxy; a.doSomething(); InterfaceB b = (InterfaceB) proxy; b.doSomething();
Then it must pass Method objects with different declaration classes. I'm not sure how it works, so this will need to be tested.
Brian source share