org.perfectable.introspection.proxy.ForwardingHandler Maven / Gradle / Ivy
package org.perfectable.introspection.proxy;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Invocation handler that delegates all calls to actual object.
*
* This class is mutable, the target can be swapped while proxies are used.
*
* @param type of objects handled
*/
public final class ForwardingHandler implements InvocationHandler<@Nullable Object, Exception, MethodInvocation> {
private T target;
/**
* Creates handler with specified object as a delegate.
*
* @param target delegate target
* @param type of proxy/target
* @return handler that forwards to {@code target}
*/
public static ForwardingHandler of(T target) {
return new ForwardingHandler<>(target);
}
private ForwardingHandler(T target) {
this.target = target;
}
/**
* Changes target to provided one.
*
* @param newTarget new delegation target
*/
public void swap(T newTarget) {
this.target = newTarget;
}
@Override
public @Nullable Object handle(MethodInvocation invocation) throws Exception {
return invocation.withReceiver(target).invoke();
}
}