how to get parameter's annotation in java?

2020-04-01 08:15发布

问题:

I'm a new Java programmer. Following is my code:

    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)

I want to get all filed's annotations. Some fields are annotated and some ain't.

I know how to use method.getParameterAnnotations() function, but it just returns three annotations.

I don't know how to correspond them.

I expect the following result:

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:

getParameterAnnotations returns one array per parameter, using an empty array for any parameter which doesn't have any annotations. For example:

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

This gives output:

0 annotatations
1 annotatations

That shows that the first parameter has no annotations, and the second parameter has one annotation. (The annotation itself would be in the second array, of course.)

That looks like exactly what you want, so I'm confused by your claim that getParameterAnnotations "only returns 3 annotations" - it will return an array of arrays. Perhaps you're somehow flattening the returned array?