建议中有多个带注释的参数值

时间:2013-10-16 11:16:51

标签: spring aspectj spring-aop

如何在我的建议中获得带注释参数的值。我有一个类似的场景:

@Custom
public void xxxx(@Param("a1") Object a, @Param("a2") Object b)
{
    //TODO
}

我希望为具有@Custom注释的所有方法定义切入点,这里没什么好看的。问题是我想在建议中获取用@Param标记的参数和注释本身的值。此类带注释参数的数量不固定,可能有任何数字或根本没有。

到目前为止,我已经使用了反射,并且我能够使用注释标记get参数,但不能注释注释的值。

1 个答案:

答案 0 :(得分:1)

这就是我获得注释的价值:

我的注释是@Name:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.PARAMETER)
@interface Name {
    String value();
}

并且负责获取它的代码:

Annotation[][] parametersAnnotations = method.getParameterAnnotations();

for (int i = 0; i < parametersAnnotations.length; i++) {
    Annotation[] parameterAnnotations = parametersAnnotations[i];
    Annotation nameAnnotation = null;

    for (Annotation annotation : parameterAnnotations) {
        if (annotation.annotationType().equals(Name.class)) {
            nameAnnotation = annotation;
            break;
        }
    }

    if (nameAnnotation != null) {
        String textInAnnotation = ((Name)nameAnnotation).value();
    }
}