@Override public boolean checkForChange(DirectCallPolicy previousPolicy) { // first setup if (previousPolicy == NOP) { return true; } // twice setup if (previousPolicy instanceof OneShotDirectCallPolicy) { throw new DirectCallException("already expecting a direct call on <" + ((OneShotDirectCallPolicy) previousPolicy).expectedInstance + "> but here's a new request for <" + expectedInstance + ">"); } // we are inside full stack direct call => do not change anything if (previousPolicy instanceof FullStackDirectCallPolicy && ((FullStackDirectCallPolicy) previousPolicy).checkWeAreDeepInsideStack()) { return false; } // unexpected throw new DirectCallException("Direct call policy is already set to " + previousPolicy); } }
@Override public DirectCallPolicy onMethodInvocationFinished(Object target) { if (expectedInstance == null) { // error happened return NOP; } if (depth < 0) { throw new DirectCallException("Stack depth is negative: " + depth + ", target: " + expectedInstance); } if (shouldBeDirect(target) && depth-- == 0) { return NOP; } return this; }
@Override public boolean shouldCallDirectly(Object target) { if (expectedInstance == null) { return false; } if (expectedInstance != target) { Object expected = expectedInstance; expectedInstance = null; throw new DirectCallException("expected to perform direct call on <" + expected + "> but got <" + target + ">"); } return true; } }
public SafeDirectCallPolicy(Object directInstance) { if (directInstance == null) { throw new DirectCallException("Direct call target cannot be null, use class instance for static calls"); } this.expectedInstance = directInstance; }
@Override public boolean checkForChange(DirectCallPolicy previousPolicy) { // first setup if (previousPolicy == NOP) { return true; } // we are inside full stack direct call => do not change anything if (previousPolicy instanceof FullStackDirectCallPolicy && ((FullStackDirectCallPolicy) previousPolicy).checkWeAreDeepInsideStack()) { return false; } // unexpected, bad setup throw new DirectCallException("Direct call policy is already set to " + previousPolicy); }