Proxy
A proxy implements the same interface as a real object and controls access to it. It may create the real object lazily, enforce security, cache, or send the call across the network.
Detailed Explanation
The caller holds a Mailer. The object is a proxy. The first send might open a connection, check a permission, or forward to another JVM. The real SmtpMailer is hidden. That stand-in is a proxy.
Kinds: virtual (lazy create), protection (access control), remote (RMI, HTTP client stubs), smart (reference counting, caching). Hibernate lazy-loads entities with proxies. Spring AOP wraps beans with JDK dynamic proxies or CGLIB subclasses.
java.lang.reflect.Proxy builds an interface proxy at runtime. You supply an InvocationHandler. Every method hits invoke. CGLIB and Byte Buddy subclass a concrete class when there is no interface. final methods and classes cannot be proxied that way.
Proxy vs decorator: both wrap and implement the same type. A decorator is the extra behaviour stacked on a real instance you already have. A proxy controls access and may not have constructed the real instance yet, or the real instance may live elsewhere. In practice the code looks similar.
You reach for a proxy when the extra job is about access, location, or lifetime. You reach for a decorator when you already have the object and want to add features. You reach for an adapter when the interface differs.
The cost of a JDK proxy is reflection and an extra stack frame. The cost of proxying everything is a system you cannot debug. The cost of this escaping from the real object (self-invocation) is that the proxy is skipped: Spring's @Transactional on a self-call does not run. Call through the injected proxy, not this.
equals on proxies is messy. Compare business ids, not the wrapper.
Code Examples
interface Image {
int size();
}
class DiskImage implements Image {
DiskImage() {
System.out.println("load");
}
@Override
public int size() {
return 10;
}
}
class LazyImage implements Image {
private Image real;
@Override
public int size() {
if (real == null) {
real = new DiskImage(); // create on first use
}
return real.size();
}
public static void main(String[] args) {
Image img = new LazyImage();
System.out.println("ready");
System.out.println(img.size());
// prints:
// ready
// load
// 10
}
}Common Gotchas
Self-invocation `this.method()` skips the proxy
inject yourself or use a different structure.
JDK proxies need an interface
a concrete class needs subclass proxies.
Treating proxy `==` the real object fails
Treating proxy `==` the real object fails