2012-05-14 27 views
0

從以下前面的問題(AspectJ - Presence of annotation in join point expression not recognized)的名單,AspectJ的 - 檢索註釋參數

我的目標: 在一個方面,我希望能夠提取/從匹配函數檢索所有註釋參數,無事情有多少。 (然後應用上的一些治療,但它不是這個問題的範圍)

所以,就目前而言,這是我做了什麼(不工作):

@Before("execution (* org.xx.xx.xx..*.*(@org.xx.xx.xx.xx.xx.Standardized (*),..))") 
public void standardize(JoinPoint jp) throws Throwable { 
    Object[] myArgs = jp.getArgs(); 
    getLogger().info("Here: arg length=" + myArgs.length); 
    // Roll on join point arguments 
    for (Object myParam : myArgs) { 

     getLogger().info(
        "In argument with " + myParam.getClass().getAnnotations().length 
           + " declaread annotations"); 
     getLogger().info("Class name is " + myParam.getClass().getName()); 
     // Get only the one matching the expected @Standardized annotation 
     if (myParam.getClass().getAnnotation(Standardized.class) != null) { 
      getLogger().info("Found parameter annotated with @Standardized"); 
      standardizeData(myParam.getClass().getAnnotation(Standardized.class), myParam); 
     } 
    } 
} 

這是意見一致的代碼:

public boolean insertLog(@Standardized(type = StandardizedData.CLIPON) CliponStat theStat) { 
    // ... 
} 

並通過JUnit測試所產生的痕跡:

INFO: ICI: arg lenght=1 
INFO: In argument with 0 declaread annotations 

看起來它不脫tect註釋

所以我的問題是:如何檢測具有特定註釋的參數?

有人知道該怎麼做嗎?

在此先感謝您的幫助。

問候。

編輯:我發現這個線程Pointcut matching methods with annotated parameters,同樣的事情討論,並應用於給定的解決方案,但它不工作..

回答

7

我希望我理解你的權利。

myParam.getClass().getAnnotations()給你一個類的註釋。喜歡的東西:

@Standardized(type = StandardizedData.CLIPON) 
public class Main{...} 

也許這個切入點/建議可以幫助你:

@Before("execution (* org.xx.xx.xx..*.*(@org.xx.xx.xx.xx.xx.Standardized (*),..))") 
public void standardize(JoinPoint jp) throws Throwable { 
    Object[] args = jp.getArgs(); 
    MethodSignature ms = (MethodSignature) jp.getSignature(); 
    Method m = ms.getMethod(); 

    Annotation[][] parameterAnnotations = m.getParameterAnnotations(); 

    for (int i = 0; i < parameterAnnotations.length; i++) { 
     Annotation[] annotations = parameterAnnotations[i]; 
     System.out.println("I am checking parameter: " + args[i]); 
     for (Annotation annotation : annotations) { 
      System.out.println(annotation); 

      if (annotation.annotationType() == Standardized.class) { 
       System.out.println("we have a Standardized Parameter with type = " 
         + ((Standardized) annotation).type()); 
      } 
     } 
    } 
} 

這給了我下面的輸出:

I am checking parameter: [email protected] 
@annotation.Standardized(type=CLIPON) 
we have a Standardized Parameter with type = CLIPON 
+0

嗨弗雷德,是的,你說得對。那就是我最終在夜晚實施的。它在開始時並沒有工作,但是因爲我犯了另一個錯誤(我在接口和實現類中註釋了方法中的參數,並且似乎寄生在正常行爲中,我已經從接口中刪除了註釋,並且它工作正常。感謝您的幫助。 – kij