2015-02-23 94 views
0

如何獲得註釋值,我有類人:在Java反射

@Retention(RetentionPolicy.RUNTIME) 
@interface MaxLength { 
int length(); 
} 

@Retention(RetentionPolicy.RUNTIME) 
@interface NotNull { 

} 

public class Person { 

private int age; 

private String name; 

public Person(int age, String name) { 
    this.age = age; 
    this.name = name; 
} 

@NotNull 
public int getAge() { 
    return this.age; 
} 

@MaxLength(length = 3) 
public String getName() { 
    return this.name; 
} 


} 

然後我試圖打印的Peson對象的方法標註值。

for (Method method : o.getClass().getDeclaredMethods()) { 
     if (method.getName().startsWith("get")) { 
      Annotation[] annotations = method.getDeclaredAnnotations(); 
      for (Annotation a : annotations) { 
       Annotation annotation = method.getAnnotation(a.getClass()); 
        System.out.println(method.getName().substring(3) + " " + 
          annotation); 
      } 
     } 
    } 

我希望它打印註釋值,但它會打印null。我不太明白我做錯了什麼。

+0

當你有'Annotation a'使用它時,不要再查找它。如果你在調試器中看看這段代碼,它應該更清晰。 – 2015-02-23 11:56:41

+0

@PeterLawrey它現在打印「@MaxLength(length = 3)」,但我只想要「3」,我找不到具體的批註工作方式。 – user2950602 2015-02-23 12:16:36

回答

0

您必須訪問註釋,如下所示。已經修改了代碼位:

Person personobject = new Person(6, "Test"); 
MaxLength maxLengthAnnotation; 
Method[] methods = personobject.getClass().getDeclaredMethods(); 
for (Method method : methods) { 
if (method.getName().startsWith("get")) { 
    // check added to avoid run time exception 
    if(method.isAnnotationPresent(MaxLength.class)) { 
     maxLengthAnnotation = method.getAnnotation(MaxLength.class); 
     System.out.println(method.getName().substring(3) + " " + maxLengthAnnotation.length()); 
    }; 
    } 
} 
+0

我假設我不知道註釋是什麼。 – user2950602 2015-02-23 12:12:51

+0

如果您不知道註釋是什麼,您將如何知道註釋的哪個屬性是必需的?就像我們試圖通過'maxLengthAnnotation.length()'來訪問'lenght'屬性,所以如果你不知道什麼是註解,你將如何確定要讀取哪個屬性? – 2015-02-23 12:18:25

0

使用註釋類名一樣 -

method.getAnnotation(MaxLength.class); 
method.getAnnotation(NotNull.class); 

或者您可以使用其他的功能得到所有註釋陣列 -

Annotation annotations[] = method.getAnnotations(); 

和迭代的註解