Given the following dynamic java proxy with an invocation handler that has internal state which changes during invocation:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
Test test = (Test) Proxy.newProxyInstance(
Test.class.getClassLoader(),
new Class[] { Test.class },
new MyInvocationHandler(true));
test.doWork();
test.doWork();
}
public interface Test {
void doWork();
}
public static class MyInvocationHandler implements InvocationHandler {
private boolean flag;
public MyInvocationHandler(boolean flag) {
this.flag = flag;
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
if ("doWork".equals(method.getName())) {
System.out.println("Flag is " + flag);
}
if (flag) {
flag = false;
// Do somemthing
}
return null;
}
}
}
I expect this to write the following to stdout:
Flag is true
Flag is false
However when debugging step by step, it outputs:
Flag is false
Flag is false
I'm using Java 11.0.5 and IntelliJ IDEA for debugging.
Does someone know what happened here?