2011-11-02 21 views
23

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

回答

35

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個註釋」 - 它會返回一個數組陣列。也許你在某種程度上扁平化返回的數組?

相關問題