165. Dynamic proxies

Dynamic proxies can be used to support the implementation of different functionalities that are part of the Cross Cutting-Concerns (CCC) category. CCC are those concerns that represent ancillary functionalities of the core functionalities, such as database connection management, transaction management (for example, Spring @Transactional), security, and logging.

More precisely, Java Reflection comes with a class named java.lang.reflect.Proxy, the main purpose of which is to provide support for creating dynamic implementations of interfaces at runtime. Proxy reflects on the concrete interface's implementation at runtime.

We can think of Proxy as a front-wrapper that pass our invocations to the right methods. Optionally, Proxy can interfere in the process before delegating the invocation.

Dynamic proxies rely on a single class (InvocationHandler) with a single method (invoke()) as in the following diagram:

If we depict the flow from this diagram, then we obtain the following steps:

  1. The actors call the needed methods through the exposed dynamic proxy (for example, if we want to call the List.add() method, we will do it through a dynamic proxy, not directly)

  2. The dynamic proxy will dispatch the invocation to an instance of an InvocationHandler implementation (each proxy instance has an associated invocation handler)

  3. The dispatched invocation will hit the invoke() method as a triad containing the proxy object, the method to invoke (as a Method instance) and an array of arguments for this method

  4. The InvocationHandler will run additional optional functionalities (for example, CCC) and will invoke the corresponding method

  5. The InvocationHandler will return the result of invocation as an object

If we try to resume this flow, then we can say that a dynamic proxy sustains invocations of multiple methods of arbitrary classes via a single class (InvocationHandler) with a single method (invoke()).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.41.205