Junior — Middle
How can you invoke the original method of an object after applying a proxy?
sobes.tech AI
Answer from AI
In Java, if you use a dynamic proxy (for example, via java.lang.reflect.Proxy), the method call on the object is handled through the implementation of the InvocationHandler interface. To invoke the original method of the object after applying the proxy, you need to explicitly call the corresponding method on the original object within the invoke method.
Example:
public class MyInvocationHandler implements InvocationHandler {
private final Object original;
public MyInvocationHandler(Object original) {
this.original = original;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// You can add additional logic before the call
System.out.println("Before method call");
// Call the original method on the original object
Object result = method.invoke(original, args);
// You can add additional logic after the call
System.out.println("After method call");
return result;
}
}
Thus, the proxy intercepts the call, and inside invoke, you call the original method via method.invoke(original, args).