What are Dynamic Proxy classes and why would I use one?

Viewed 59072

What is a use case for using a dynamic proxy?

How do they relate to bytecode generation and reflection?

Any recommended reading?

5 Answers

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. It can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class. Dynamic proxy classes are useful to an application or library that needs to provide type-safe reflective dispatch of invocations on objects that present interface APIs.

Dynamic Proxy Classes

One use case is hibernate - it gives you objects implementing your model classes interface but under getters and setters there resides db related code. I.e. you use them as if they are just simple POJO, but actually there is much going on under cover.

For example - you just call a getter of lazily loaded property, but really the property (probably whole big object structure) gets fetched from the database.

You should check cglib library for more info.

Related