Video in progress

Strong Middle ☕ Core Java

How does java.lang.reflect.Proxy work, and what is its limitation?

Proxy.newProxyInstance builds a class at runtime that implements the given interfaces and sends every call to InvocationHandler.invoke. The limitation is that it works only with interfaces: it can't proxy an ordinary class.

📖 Answer

A small example, a proxy that measures the time of each call:

@SuppressWarnings("unchecked")
static <T> T timed(T target, Class<T> iface) {
    return (T) Proxy.newProxyInstance(
        iface.getClassLoader(),
        new Class<?>[]{iface},
        (proxy, method, args) -> {
            long t = System.nanoTime();
            try {
                return method.invoke(target, args);
            } catch (InvocationTargetException e) {
                throw e.getCause();          // unwrap the original exception
            } finally {
                log.info("{} {} mks", method.getName(), (System.nanoTime() - t) / 1000);
            }
        });
}

PaymentService svc = timed(new PaymentServiceImpl(), PaymentService.class);

Where people trip:

  • method.invoke wraps the original exception in an InvocationTargetException: if you don't unwrap it, the caller gets an unexpected exception. If a checked exception isn't declared in the interface, you get UndeclaredThrowableException;
  • equals, hashCode and toString come to the handler too;
  • a this.otherMethod() call inside the proxy target doesn't go through the proxy: this is the root of the Spring problem "@Transactional doesn't work on self-invocation".

Proxying a class requires bytecode generation: CGLIB or ByteBuddy creates a subclass. That's why it can't intercept a final class or final methods. Even when there's an interface, Spring picks CGLIB by default (proxyTargetClass=true, since Boot 2).