Search code examples
javaproxydynamic-proxy

In Java how instance of and type cast(i.e (ClassName)) works on proxy object?


Java generates a proxy class for a given interface and provides the instance of the proxy class. But when we type cast the proxy object to our specific Object, how java handles this internally? Is this treated as special scenario?

For example I have class OriginalClass and it implements OriginalInterface, when I create proxy object by passing OriginalInterface interface Java created proxy class ProxyClass using methods in the provided interface and provides object of this class(i.e. ProxyClass). If my understanding is correct then can you please answer following queries

  1. When I type cast object of ProxyClass to my class OriginalClass this works, but how Java is allowing this? Same in case of instace of?
  2. As my knowledge Java creates a proxy class only with the methods, but what happen when I try to access attributes on this object?
  3. Only interface methods are getting implemented in proxy, but what happens when I try to access a method which not in interface and only mentioned in the class?

Thanks, Student


Solution

  • Java isn't allowing casting from a proxy to a concrete class. JDK proxies (java.lang.reflect.Proxy) are only proxies of an interface. The resulting proxy is of type ProxyX (X being a number), and if you try to cast it to any class you will get ClassCastException

    Therefore your 2nd and 3rd questions aren't relevant - the proxy isn't backed by a concrete class. To achieve this, you can use other proxying mechanisms - CGLIB or javassist. They use ynamic subclassing, and so all protected (and above) fields and methods are accessible to the subclass (proxy).