Java Reference
In-Depth Information
The results from the execution are shown here:
Real before
Before-test
Some text for test purpose
After-test
Real after
What's obvious is that the @Before methods are executed before the intercept-
Before method of the interceptor, and the @After methods are executed after the
interceptAfter method. We'll use this feature shortly.
But let's move on and make another interceptor, this time more valuable than just
logging some text to the screen. Listing B.6 shows a sample interceptor that's used for
timing purposes.
Listing B.6
Second interceptor— SampleTimingIntercept or
[...]
public class SampleTimingInterceptor implements Interceptor {
Timer timer = new Timer();
B
C
public void interceptBefore() {
System.out.println("Interceptor started.");
timer.start();
}
D
E
public void interceptAfter() {
timer.stop();
System.out.println("Interceptor ended.”
+ “The test executed for " + timer.time());
}
class Timer {
private long nanoStart = 1;
private long nanoEnd = 0;
void start() {
nanoStart = System.nanoTime();
}
void stop() {
nanoEnd = System.nanoTime();
}
long time() {
return nanoEnd - nanoStart;
}
}
}
Again, for this interceptor to be a valid interceptor according to our terms, it needs
to implement the Interceptor interface B . In C we declare a local timer vari-
able of type Timer , which we use to time the execution of the test method. The
 
Search WWH ::




Custom Search