2017-03-07 50 views
1

我正在使用ByteBuddy進行一些certian方法的性能測量。因此,我正在註解這些互動的。由於該方法的簽名並不穩定,我選擇了通用的方式爲我攔截:如何使用ByteBuddy測量通過代理注入的註釋標記方法所花費的時間

public class ChronometryInterception { 

    @RuntimeType 
    public Object intercept(@Origin MethodHandle methodHandle, @AllArguments Object[] allArguments, @Origin Method method) throws Exception { 
    System.out.println("in interceptor"); 
    long startTime = System.currentTimeMillis(); 
    try { 
     return methodHandle.invoke(allArguments); 
    } catch (Throwable e) { 
     System.out.println("ex in interceptor " + e.getMessage()); 
     throw new Exception(e); 
    } finally { 
     long elapsedTime = System.currentTimeMillis() - startTime; 
     System.out.println("took " + elapsedTime; 

    } 
    } 
} 

,我將它綁定在我的premain()這樣的

ChronometryInterception chronometryInterception = new ChronometryInterception(); 

new AgentBuilder.Default() 
    .with(AgentBuilder.Listener.StreamWriting.toSystemOut()) 
    .type(declaresMethod(isAnnotatedWith(Timed.class))) 
     .transform((builder, type, classLoader, module) -> builder 
     .method(isAnnotatedWith(Timed.class)) 
       .intercept(MethodDelegation.to(chronometryInterception)) 
    ).installOn(instrumentation); 

在聽衆流,我可以看到註釋類已經改變了,他們試圖做一些事情,但最終還是NPE。使用調試器,我沒有在ChronometryInterception中找到任何地方。任何出路?謝謝!

+0

您能給出異常的堆棧跟蹤嗎?另外,嘗試將攔截方法定義爲「靜態」,而不是委託給實例。 –

回答

1

我找到了一個可行的解決方案。最後,我攔截器的方法簽名不好。即使在ChronometryInterception的一個實例中,這個工作正常:

public class ChronometryInterception { 

    @RuntimeType 
    public Object intercept(@SuperCall Callable<?> zuper) throws Exception { 
    long startTime = System.currentTimeMillis(); 
    try { 
     return zuper.call(); 
    } catch (Exception e) { 
     throw e; 
    } finally { 
     long elapsedTime = System.currentTimeMillis() - startTime; 
     System.out.println("took " + elapsedTime); 
    } 
    } 

}