Search code examples
javainterfaceencapsulationextend

How to make object returned by java.lang.reflect.Proxy.newProxyInstance() to extend other class


newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h); 

Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.

I need to encapsulate instance returned by this method (for example,into some other class) so, that it will also extend other class. So the final class will extend one class and implement specified interfaces.

class to extend is:

public class IProxy {

ObjectRef oref;

public IProxy(ObjectRef oref) {
    this.oref = oref;
}

}

so the process should be :

MyInterface() mi=(MyInterface) newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h);

// some magic trick

and in the end I would like to have instance of class that extends IProxy and implements all interfaces that mi did implement.


Solution

  • You cannot do it, because the object returned from newProxyInstance already inherits from some other class, and you cannot inherit from two classes in Java.

    You need to keep oref as an instance variable of your class that implements the InvocationHandler interface. You will initialize oref in the constructor of the InvocationHandler, and provide an interface to access oref through a method:

    public interface IProxy {
        ObjectRef getOref();
    }
    

    Your InvocationHandler should respond to calls of getOref by returning its oref member.