AspectJ - 检索带注释的参数列表

时间:2012-05-14 10:11:53

标签: annotations aspectj

来自上一个问题(AspectJ - Presence of annotation in join point expression not recognized),

我的目标: 在一个方面,我希望能够从匹配的函数中提取/检索所有带注释的参数,无论有多少。 (然后应用一些处理,但这不是这个问题的范围)

所以目前,这就是我所做的(不工作):

@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

看起来它没有检测到注释

所以我的问题是:如何检测具有特定注释的参数?

有人知道怎么做吗?

提前感谢您的帮助。

问候。

编辑:我找到了这个帖子Pointcut matching methods with annotated parameters,讨论了同样的事情,并应用了给定的解决方案,但它没有工作..

1 个答案:

答案 0 :(得分:10)

我希望我理解你。

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:  main.CliponStat@331f2ee1 
@annotation.Standardized(type=CLIPON)
we have a Standardized Parameter with type = CLIPON