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
ProxyClass
to my class OriginalClass
this works, but how Java is allowing this? Same in case of instace of?Thanks, Student
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).