2012-09-21 19 views
3

我目前在項目工作中的Liferay中,我想能夠訪問我的方法和參數都指定了這些方法,在歷史上。這是在某些代碼塊出現異常的情況下完成的。我已經搜索過,很容易得到方法名稱歷史(Thread.currentThread()。getStackTrace();)但我想知道什麼參數給這些方法。訪問方法和參數的歷史與Java

例如:

public class A { 
    public static void main(String[] Args) { 
     try { 
      System.out.println(new B().someMethod(5)); 
     } catch (Exception e) { 
      //GET HISTORY 
     } 
    } 
} 

public class B { 
    public int someMethod(int i) throws Exception { 
     i += 2; 
     throw new Exception("Expected Exception to Generate History Search"); 
     return i; 
    } 
} 

是否有可能瞭解我怎麼能在A級,當我捕捉到了異常,所有這些數據?那麼,我該怎麼做?

+1

僅限於您自己捕獲該數據。 –

+0

我個人的做法是創建一個包裝程序,該程序修改非抽象方法以在調用時存儲名稱/參數數據。 – Vulcan

回答

1

您可以使用Aspect Oriented Programming。例如,看AspectJ

以下方面將跟蹤程序執行期間的所有公共方法調用。 這可能是微調用自己的要求工作。例如,切入點可以調整爲只攜帶自己的包。可以將打印語句更改爲使用某些日誌記錄框架。

public aspect Trace { 
    pointcut publicMethodExecuted(): execution(public * *(..)); 

    after(): publicMethodExecuted() { 
     System.out.printf("Enters on method: %s. \n", thisJoinPoint.getSignature()); 

     Object[] arguments = thisJoinPoint.getArgs(); 
     for (int i =0; i < arguments.length; i++){ 
      Object argument = arguments[i]; 
      if (argument != null){ 
       System.out.printf("With argument of type %s and value %s. \n", argument.getClass().toString(), argument); 
      } 
     } 
     System.out.printf("Exits method: %s. \n", thisJoinPoint.getSignature()); 
    } 
} 
+1

謝謝。我正在研究它一些,但後來我的一位同事告訴我,我必須使用Log4J,但是你的answear將我推向了正確的方向;) –

0

你應該考慮在你的應用程序中使用記錄。

0

你一定要在看在你的應用程序登錄。如果你想避免混淆你的代碼太多(我個人討厭在每個方法的開始和結束處使用常量log.debug(...)),請考慮使用Aspect Oriented Programming(面向方面​​編程)(谷歌可以爲它提供很多好的指南,或者有一個體面的aop引導使用Spring here,只是向下滾動到LoggingAspect),這將讓你簡單地註釋方法,或者你希望記錄整個類。