2013-05-29 67 views
0

我想知道如何使用param1(在TestClassGeneralMeasuraments類的方法中定義並使用參數)可以調用doMonitorization方法,該方法具有正確的註釋它具有攔截AspectJ定義,如下面的代碼所示。AspectJ/Java工具來攔截註釋參數調用/用法

package monitorization; 

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.annotation.After; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Pointcut; 

@Aspect 
public class AspectJInterceptor { 
    @Pointcut(value = "@annotation(monitorme)", argNames = "monitorme") 
    public void monitorActivity(Monitorme monitorme) {} 

    @After("monitorActivity(monitorme)") 
    public void doMonitorization(JoinPoint jp, Monitorme monitorme) { 
     MetricsDataStructure.staticInstance.addOperation(jp.getSignature().toLongString(), monitorme.value()); 
    } 
} 

/////////////////////// //////

package monitorization; 

import java.lang.annotation.Retention; 
import java.lang.annotation.Target; 
import java.lang.annotation.ElementType; 
import java.lang.annotation.RetentionPolicy; 

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Monitorme { 
    int value(); 
} 

///////////////// ////////////

package monitorization; 

public class TestClassGeneralMeasuraments{ 
    @Monitorme(20) 
    int field; 
    @Monitorme(50) 
    int field2; 

    @Monitorme(5) 
    public void simpleTestMethod(@Monitorme(10) String param1){ 
     this.field = 1; 

     this.field = 3; 

     this.field = 4; 

     param1 = ""; 
    } 

    @Monitorme(30) 
    public void simpleTestMethod2(@Monitorme(10) String param1){ 
     this.field2 = 1; 
     this.field2 = 1; 
     param1 = ""; 
    } 

    public static void main(final String[] args){ 
     long intialTimeStamp = System.currentTimeMillis(); 
     System.out.println("Starting up"); 
     TestClassGeneralMeasuraments testObject = new TestClassGeneralMeasuraments(); 
     for(long i=0; i<50; i++) 
     { 
      testObject.simpleTestMethod("Hey"); 
      testObject.simpleTestMethod("Hey"); 
      testObject.simpleTestMethod2(""); 
     } 
    } 
} 

回答

2

AspectJ的切入點@annotation不能只匹配在參數類型的參數標註,即你不能匹配

public foo(@MyAnnotation MyType foo) 

但如果類MyType@MyAnnotation註釋你只能匹配

public foo(MyType foo) 

這已在AspectJ郵件列表中討論過,並且是希望列表中的一項功能,迄今尚未實現。

+0

非常感謝你的回答,而AspectJ應該實現這個功能它會有所作爲。謝謝@ kriegaex! – Axel