如何在java中获取参数注释?

时间:2011-11-02 07:07:12

标签: java reflection annotations

我是一名新的Java程序员。以下是我的代码:

    public void testSimple1(String lotteryName,
                        int useFrequence,
                        Date validityBegin,
                        Date validityEnd,
                        LotteryPasswdEnum lotteryPasswd,
                        LotteryExamineEnum lotteryExamine,
                        LotteryCarriageEnum lotteryCarriage,
                        @TestMapping(key = "id", csvFile = "lottyScope.csv") xxxxxxxx lotteryScope,
                        @TestMapping(key = "id", csvFile = "lotteryUseCondition.csv") xxxxxxxx lotteryUseCondition,
                        @TestMapping(key = "id", csvFile = "lotteryFee.csv") xxxxxxxx lotteryFee)

我想获得所有提交的注释。有些字段是注释的,有些则不是。

我知道如何使用method.getParameterAnnotations()函数,但它只返回三个注释。

我不知道如何对应它们。

我希望得到以下结果:

lotteryName - none
useFrequence- none
validityBegin -none
validityEnd -none
lotteryPasswd -none
lotteryExamine-none
lotteryCarriage-none
lotteryScope - @TestMapping(key = "id", csvFile = "lottyScope.csv")
lotteryUseCondition - @TestMapping(key = "id", csvFile = "lotteryUseCondition.csv")
lotteryFee - @TestMapping(key = "id", csvFile = "lotteryFee.csv")

1 个答案:

答案 0 :(得分:38)

getParameterAnnotations为每个参数返回一个数组,对任何没有任何注释的参数使用空数组。例如:

import java.lang.annotation.*;
import java.lang.reflect.*;

@Retention(RetentionPolicy.RUNTIME)
@interface TestMapping {
}

public class Test {

    public void testMethod(String noAnnotation,
        @TestMapping String withAnnotation)
    {
    }

    public static void main(String[] args) throws Exception {
        Method method = Test.class.getDeclaredMethod
            ("testMethod", String.class, String.class);
        Annotation[][] annotations = method.getParameterAnnotations();
        for (Annotation[] ann : annotations) {
            System.out.printf("%d annotatations", ann.length);
            System.out.println();
        }
    }
}

这给出了输出:

0 annotatations
1 annotatations

这表明第一个参数没有注释,第二个参数有一个注释。 (当然,注释本身将位于第二个数组中。)

这看起来就像你想要的那样,所以我对你声称getParameterAnnotations“只返回3个注释”感到困惑“ - 它将返回一个数组数组。也许你在某种程度上弄平了返回的数组?