如何在 Java 中获取参数的注释?



我是一名新的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")

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个注释"感到困惑-它将返回数组的数组。也许你在某种程度上扁平化了返回的数组?

相关内容

  • 没有找到相关文章

最新更新