我有一個對象調用計數器基本上是這樣的:
private long count;
private long errors;
private long duration;
private long errorDuration;
有兩個「時間」的方法定時返回的東西,其它方法都是無效的方法。
public <T> T time(ReturningRunnable<T> runnable) {
long start = currentTimeMillis();
T result = null;
try {
result = runnable.run();
} catch (Throwable ex) {
errorDuration += currentTimeMillis() - start;
errors++;
throw runtime(ex);
}
duration += currentTimeMillis() - start;
count++;
return result;
}
public void time(Runnable runnable) {
time(new RunnableRunner(runnable));
}
我選擇重新拋出異常的運行時異常(如我不是checked異常的粉絲),但你也可以同樣讓您的自定義MyRunnable接口拋出異常,只是趕上並重新拋出他們。下面是上面的用法:
counter.time(new Runnable() {
@Override
public void run() {
// Do something
});
或者這一點,在返回值的情況下:
return counter.time(new ReturningRunnable<Integer>() {
@Override
public Integer run() {
return 1; // You get the idea
});
我喜歡這個,因爲我的櫃檯對象可以暴露在JMX和注射的地方,我需要他們。你可以用反射來做你所要求的,但我認爲這會很麻煩(恕我直言)。
見java.lang.reflect.Method中。 – 2011-05-19 15:45:12