Proxy
A stand-in that controls access to another object — virtual (lazy), protection, remote, caching and logging proxies, dynamic proxies in Java, JavaScript Proxy objects, and how frameworks use them.
Intent: provide a surrogate or placeholder for another object to control access to it. The proxy has the same interface as the real object, so clients can't tell the difference.
Kinds of proxy
| Kind | Controls | Example |
|---|---|---|
| Virtual | When the real object is created | Lazy-load a big image or an ORM relation on first access |
| Protection | Who may call it | Check permissions before delegating |
| Remote | Where it lives | A local stub for an object on another machine (gRPC stubs, Java RMI) |
| Caching | Whether to call at all | Return cached results for repeated calls |
| Logging / metrics | Observes calls | Record timings and arguments |
| Smart reference | Lifecycle | Reference counting, releasing resources |
Virtual proxy (lazy loading)
interface Image { void display(); }
class HighResImage implements Image {
private final byte[] pixels;
HighResImage(String path) { this.pixels = loadFromDisk(path); } // slow
public void display() { /* draw pixels */ }
}
class LazyImage implements Image {
private final String path;
private HighResImage real; // not loaded yet
LazyImage(String path) { this.path = path; }
public void display() {
if (real == null) real = new HighResImage(path); // load on first use
real.display();
}
}
List<Image> gallery = paths.stream().map(LazyImage::new).toList(); // instant
gallery.get(0).display(); // only this one loadsclass HighResImage:
def __init__(self, path):
self.pixels = load_from_disk(path) # slow
def display(self): ...
class LazyImage:
def __init__(self, path):
self._path, self._real = path, None
def display(self):
if self._real is None:
self._real = HighResImage(self._path)
self._real.display()
# Or, for attributes: functools.cached_property computes on first accessinterface Image { display(): void; }
class LazyImage implements Image {
private real?: HighResImage;
constructor(private path: string) {}
display() {
(this.real ??= new HighResImage(this.path)).display();
}
}Protection and caching proxies
class SecuredDocumentStore implements DocumentStore {
private final DocumentStore real;
private final CurrentUser user;
SecuredDocumentStore(DocumentStore real, CurrentUser user) { this.real = real; this.user = user; }
public Document get(String id) {
if (!user.canRead(id)) throw new AccessDeniedException(id);
return real.get(id);
}
public void delete(String id) {
if (!user.isAdmin()) throw new AccessDeniedException(id);
real.delete(id);
}
}class CachingWeatherClient:
def __init__(self, real, ttl=300):
self._real, self._ttl, self._cache = real, ttl, {}
def forecast(self, city: str):
hit = self._cache.get(city)
if hit and time.monotonic() - hit[1] < self._ttl:
return hit[0]
result = self._real.forecast(city)
self._cache[city] = (result, time.monotonic())
return resultclass SecuredDocumentStore implements DocumentStore {
constructor(private real: DocumentStore, private user: CurrentUser) {}
async get(id: string) {
if (!this.user.canRead(id)) throw new Error(`access denied: ${id}`);
return this.real.get(id);
}
}Dynamic proxies
Writing a proxy class per interface is tedious. Runtimes can generate them:
// java.lang.reflect.Proxy: intercept every call on any interface
@SuppressWarnings("unchecked")
static <T> T timed(T target, Class<T> iface) {
return (T) Proxy.newProxyInstance(iface.getClassLoader(), new Class<?>[]{iface},
(proxy, method, args) -> {
long start = System.nanoTime();
try { return method.invoke(target, args); }
finally {
System.out.printf("%s took %d µs%n", method.getName(), (System.nanoTime() - start) / 1000);
}
});
}
OrderRepository repo = timed(new JdbcOrderRepository(ds), OrderRepository.class);class LoggingProxy:
"""Forwards any attribute access to the wrapped object."""
def __init__(self, target):
self._target = target
def __getattr__(self, name): # called only for attributes not found on the proxy
attr = getattr(self._target, name)
if not callable(attr):
return attr
def wrapper(*args, **kwargs):
print(f"calling {name}{args}")
return attr(*args, **kwargs)
return wrapper
repo = LoggingProxy(OrderRepository())// ES6 Proxy intercepts property access, assignment, calls and more
function logged<T extends object>(target: T): T {
return new Proxy(target, {
get(obj, prop, receiver) {
const value = Reflect.get(obj, prop, receiver);
if (typeof value !== "function") return value;
return (...args: unknown[]) => {
console.log(`call ${String(prop)}`, args);
return value.apply(obj, args);
};
},
});
}
// Vue 3 reactivity and MobX are built on Proxy: 'set' traps trigger re-renders
const state = new Proxy({ count: 0 }, {
set(obj, prop, value) { obj[prop as "count"] = value; rerender(); return true; },
});How frameworks use proxies
- Spring AOP:
@Transactional,@Cacheable,@Asyncwork by wrapping your bean in a proxy (JDK dynamic proxy or CGLIB subclass) that starts a transaction, checks the cache, or submits to an executor before calling your method. - Hibernate/JPA lazy relations:
order.getCustomer()returns a proxy that loads the row on first access (and throwsLazyInitializationExceptionif the session is closed). - Mocking libraries (Mockito,
unittest.mock) generate proxies that record calls. - Vue, MobX, Immer use JS Proxies to track reads and writes.
Key takeaways
- Proxy has the same interface as the real object and controls access to it.
- Virtual (lazy), protection, remote, caching and logging are the main kinds.
- Dynamic proxies (Java Proxy, JS Proxy, getattr) intercept calls generically.
- Frameworks use proxies for transactions, lazy loading, caching and reactivity.