Method Interception
The problem
Timing, auditing, retries, and transactions are the same few lines wrapped around many methods. Written by hand they are copied into every method that needs them; written with a reflective proxy they cost the zero-reflection guarantee.
How it solves it
An annotation meta-annotated @InterceptingAnnotation marks calls to route
through interceptors. The processor emits a subclass of the bean that
overrides each intercepted method and dispatches through a chain to super:
@InterceptingAnnotation
@Retention(RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Timed {
String value() default "";
}
The interceptor is an ordinary bean marked @Intercepts, so it is injected,
scoped, and conditioned like any other:
@Singleton
@Intercepts(Timed.class)
public final class TimingInterceptor implements MethodInterceptor {
private final Metrics metrics;
@Inject
public TimingInterceptor(Metrics metrics) {
this.metrics = metrics;
}
@Override
public @Nullable Object invoke(MethodInvocation invocation) throws Throwable {
long start = System.nanoTime();
try {
return invocation.proceed();
} finally {
metrics.record(invocation.annotation().stringValue("value").orElse(invocation.methodName()),
System.nanoTime() - start);
}
}
}
The bean itself changes only by being subclassable:
public class OrderService {
@Inject
public OrderService(Repo repo) { ... }
@Timed("place")
public Order place(Cart cart) { ... }
}
Because the generated proxy is the instance the injector hands out, member
injection, @PostConstruct, scoping, and destruction are unaffected, and a
call from one bean method to another is intercepted too.
Placement and order
A class-level annotation sweeps every declared method that is not private,
static, or final, skipping Object methods, @Provides methods, and
@Inject / @PostConstruct / @PreDestroy methods. A method-level
annotation applies to that method alone.
Interceptors run in source order, first listed outermost, and class-level annotations wrap method-level ones:
@Retry
public class OrderService {
@Secured
@Timed
public Order place(Cart cart) { ... }
}
runs Retry → Secured → Timed → place. Declaring the same annotation at both
levels replaces the class-level one in place, so a method can retune
@Timed("checkout") without inheriting @Timed("") as well.
Reading and substituting arguments
MethodInvocation exposes the call site as compile-time constants — no
java.lang.reflect.Method anywhere — and proceed(Object...) substitutes
arguments for the rest of the chain, validating count and types:
@Override
public @Nullable Object invoke(MethodInvocation invocation) throws Throwable {
String raw = (String) invocation.arguments().get(0);
return invocation.proceed(raw.strip());
}
Limitations
- The bean must be subclassable. A
finalclass, arecord, anenum, asealedclass, and a generic class are each a compile error naming the reason; so is afinal,static, orprivatemethod carrying the annotation. - A method whose
throwsclause contains a type variable (for example<E extends Exception> void run() throws E) cannot be intercepted — a type variable cannot be acatchparameter. A class-level sweep skips such a method silently; annotating it directly is a compile error. - An intercepting annotation is honoured on types and methods only: placing one on a field or a parameter has no effect.
- Only method calls are intercepted: no constructor or field interception, and an interceptor cannot add methods a bean does not declare.
- Calls made from the bean's own constructor are not intercepted — the chain
is assigned after
super(...)returns, so a constructor-time call falls through to the bean's own implementation. The chain is live by the time the container runs@Injectmethods, field injection, and@PostConstruct, so a call made from any of those is intercepted.@Injectmethods run before field injection, so an interceptor invoked from one may observe a bean whose@Injectfields are still null. - A
synchronizedintercepted method still holds its monitor for the call intosuper, but the interceptors themselves run outside that lock. - Inherited methods are not swept; a class-level annotation covers declared methods only, consistent with member injection and lifecycle callbacks.
@Providesproducts and assisted beans cannot be intercepted: the container does not construct them.- Builder overrides of an intercepted bean bypass
interception entirely — an override binds a raw instance, and nothing
proxies it. Overriding the interceptor bean itself is different: it gets
test overrides for free, replacing it in every chain it participates in, not
just direct resolution — but only when the override targets the
interceptor's own key (
Key.of(TheInterceptor.class)); an override bound under a qualifier or a supertype key is not picked up by the chain. This reach-the-chain behaviour is forInjector.builder()overrides only: a child injector's binding for the interceptor's own key shadows direct resolution through the child but leaves every chain — the parent's and the child's — running the original interceptor. - There is no ordering attribute: the bean's author fixes the order by writing the annotations in the order they should run.
- An intercepting annotation with no
@Interceptsbean fails when the bean is constructed, withInterceptorResolutionExceptionnaming the annotation and the intercepted method, not at compile time and not deferred until an intercepted method is actually called — the chain is bound in the generated proxy's constructor. The interceptor may legitimately live in another artifact.