Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create proxy in java

Tags:

java

proxy

How do they create proxy of a class in java. Do they create the proxy on as needed basis or they create it and have it around forever.

like image 890
javaguy Avatar asked Jan 23 '11 22:01

javaguy


2 Answers

You can create proxies in two basic ways:

  • using the JDK mechanism, by interface. Take a look at java.lang.reflect.Proxy.
  • using some byte-code generation/manipulation library, on a concrete class. Take a look at cglib and javassist

Apache has a nice utility: commons-proxy. It wraps many mechanisms and frameworks for creating proxies.

This is all about dynamic proxies - i.e. those created at runtime. For static proxies - see wikipedia about the proxy pattern

Note that you are not making a proxy of a class - you are making a proxy of an object.

like image 123
Bozho Avatar answered Sep 19 '22 12:09

Bozho


I agree with the comments that the question is a little vague. However, I'd suggest you look at some of the mocking frameworks such as easymock and mockito. Their source code is available and their core functionality is creating proxies of class and interfaces. So they are good concrete examples of how to go about creating proxies.

like image 20
drekka Avatar answered Sep 22 '22 12:09

drekka