2011-11-02 37 views
23

Tôi là một lập trình viên Java mới. Sau đây là mã của tôi:cách nhận chú thích của tham số trong 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) 

Tôi muốn nhận tất cả chú thích của tệp. Một số trường được chú thích và một số trường thì không.

Tôi biết cách sử dụng hàm method.getParameterAnnotations(), nhưng nó chỉ trả lại ba chú thích.

Tôi không biết cách tương ứng với chúng.

tôi mong đợi kết quả sau:

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") 

Trả lời

35

getParameterAnnotations lợi nhuận một mảng mỗi tham số, sử dụng một mảng trống cho bất kỳ tham số mà không có bất kỳ chú thích. Ví dụ:

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

Điều này cho phép đầu ra:

0 annotatations 
1 annotatations 

Điều đó cho thấy rằng tham số đầu tiên không có chú thích, và tham số thứ hai có một chú thích. (Tất cả chú thích sẽ nằm trong mảng thứ hai, tất nhiên.)

Điều đó giống như chính xác những gì bạn muốn, vì vậy tôi bị nhầm lẫn với khiếu nại của bạn rằng getParameterAnnotations "chỉ trả về 3 chú thích" - nó sẽ trả về một mảng mảng. Có lẽ bạn bằng cách nào đó làm phẳng mảng trở lại?

Các vấn đề liên quan