javadesign-patternsinterfacermi

Is the Java Proxy class related to the Proxy Design Pattern?


There is a class in java called Proxy: https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Proxy.html. As I understand, this is used to implement interfaces on the runtime. On the other side, when searching for this, I came across a page explaining the Proxy Design Pattern. So are they related in any way? Or are they totally separate things?


Solution

  • A frequent use of the Proxy class is indeed to implement the proxy design pattern in an automated way.

    If for example you want to automagically wrap an object inside a proxy with some additional behaviour (let's say rate limiting method calls, but it could really be anything) then Proxy lets you do this in a very general way without writing code that's specific to a given class to proxy.

    Note that this is not the only use of the Proxy class however. For example the proxy design pattern is defined in a way that the original object and the proxy have the same interface (i.e. same methods & so on) and that's not necessary for the Proxy class. The invocation handler doesn't necessary need to forward the calls to a similarly-"shaped" object, but can do whatever it wants. A common example for this is constructing mock objects.