Search code examples
javareflectiondynamic-proxy

What are Proxy in the Reflection API good for?


I am learning the concepts of reflection and I am reading "Java Reflection In action" book. I have just started with the chapter "Proxy" where it says "a proxy, that supports the interface of another object, its target, so that the proxy can substitute for the target for all practical purposes" .

Can I have a real life easy example to understand this concept of proxy please?


Solution

  • Well, proxy is just a mechanism, you can do diffrent things with and a lot of framework use them in various ways.

    Here are however "classical" areas where proxies can be used:

    • Access control: intercept invocations and perform some control check
    • Security: you can wrap/unwrap references as they flow across modules to perform checks and restrict certain actions
    • Persistence: only the proxy is available, and data are loaded on demand from another storage medium
    • Lazy loading: the proxy load or compute information only when needed
    • Asynchrony: the proxy is a handle for a result that will be available later (so-called transparent future)
    • Remoting: the proxy provide the illusion of having the object localy, and deals with remote communication
    • Contracts: ensure the pre- and post-conditions are met before and after an invocation
    • AOP: aspect-oriented programming rely on the ability to intercept method invocation. One technique to do so it so use proxies.

    Note: these areas have some overlap.

    In the paper "On the design of the ECMAScript Reflection API", the authors distighuish between two main kinds of proxies:

    Generic wrappers. Proxies that wrap other objects in the same address space. Ex- ample uses include access control wrappers (e.g. revokable references), higher-order contracts [Findler and Felleisen 2002], profiling, taint tracking, etc.

    Virtual objects. Proxies that emulate other objects, without the emulated objects having to be present in the same address space. Examples include remote object proxies (emulate objects in other address spaces), persistent objects (emulate objects stored in databases), transparent futures (emulate objects not yet computed), lazily instantiated objects, test mock-ups, etc.

    I think it covers more or less the areas I describe before. But no list will be complete. There is not fixed case for proxies--it is a generic mechanism or principle.