2014-11-23 66 views
0

我有自定義的註釋類其註釋字段調用方法

@Retention(RetentionPolicy.RUNTIME) 

public @interface Range { 

     int min(); 
     int max(); 
} 

我裏面有很多場的另一個類,我想使用的註釋,以檢查該字段的值是否是在範圍。

public class AsdFile { 

@Range(min = 0, max = 59) 
private int sec; 
@Range(min = 0, max = 59) 
private int minsec; 
@Range(min = 0, max = 24) 
private int hour; 
@Range(min = 1, max = 31) 
private int day; 

,我希望寫在這個類中的方法控制這樣的

public void validateRange(int input) 
{ 
    Field[] fields = this.getClass().getDeclaredFields(); 

    for(Field field: fields) 
    { 

     if (field.isAnnotationPresent(Range.class)) 

     { 

      Range range = field.getAnnotation(Range.class); 
      int max = range.max(); 
      int min = range.min(); 
      if ((input <= max) && (input >= min)) 
      { 
       System.out.println("Value in range"); 
      } 
      else 
      { 
       System.out.println("Value is not in range"); 
      } 

     } 
    } 
} 

我想控制的具體註釋的價值,但我不知道該怎麼做的範圍是

+0

看來你的代碼沒問題。什麼是錯誤? – NFE 2014-11-23 13:09:43

+0

它檢查範圍那樣 – user2957741 2014-11-23 13:11:54

+0

秒所有註釋的字段:34 最大:59分鐘:0 價值範圍 最大:59分鐘:0 價值範圍 最大:24分鐘:0 不在範圍 最大:31min: 1 不在範圍內 max:12min:1 不在範圍內,但我想控制只是第二個 – user2957741 2014-11-23 13:12:48

回答

0

我想你想驗證特定的領域。你的代碼將在四個字段上進行驗證。

這可能會幫助你,如果我正確理解你的問題。在方法字段名即

通放慢參數:

asdFile.validateRange("sec",10); 

檢查檢查字段名稱後驗證:

public void validateRange(String fieldname, int input) 
    { 
     Field[] fields = this.getClass().getDeclaredFields(); 

     for(Field field: fields) 
     { 

      if(field.getName().equals(fieldname)){ 
      if (field.isAnnotationPresent(Range.class)) 

      { 

       Range range = field.getAnnotation(Range.class); 
       int max = range.max(); 
       int min = range.min(); 
       if ((input <= max) && (input >= min)) 
       { 
        System.out.println("Value in range"); 
       } 
       else 
       { 
        System.out.println("Value is not in range"); 
       } 

      } 
      } 
     } 
    } 

這將做驗證的「秒」只有場。

+0

謝謝你,這正是我想要的。但是這種情況違反了私人訪問修飾符。我是對的 – user2957741 2014-11-23 14:05:12

+0

是的,如果你正試圖在其他課上訪問它。 – NFE 2014-11-23 14:07:38