AspectJ/Java instrumentation to intercept an annoted parameter call/usage

夙愿已清 提交于 2019-12-13 04:57:08

问题


I would like to know how the doMonitorization method can be called when the param1 is used (param defined and used on the methods of the TestClassGeneralMeasuraments Class) which has the correct annotation that has a interception AspectJ definition as the bellow code shows.

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("");
        }
    }
}

回答1:


AspectJ @annotation pointcuts cannot match annotations on parameters, only on parameter types, i.e. you cannot match on

public foo(@MyAnnotation MyType foo)

but you can only match on

public foo(MyType foo)

if class MyType is annotated by @MyAnnotation.

This has been discussed on the AspectJ mailing list and is a feature on the wish list which has not been implemented so far.



来源:https://stackoverflow.com/questions/16810617/aspectj-java-instrumentation-to-intercept-an-annoted-parameter-call-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!