2014-10-09 170 views
1

我有一個名爲ClBranch.java像下面類:如何獲得註釋名稱屬性?

@Entity 
    @Table(name = "PROVINCE") 
    public class PROVINCE implements Serializable { 
     @Id 
     @Column(name="PR_CODE", length = 50) 
     private String provinceCode 

     @Column(name="PR_NAME", length = 500) 
     private String provinceName 
    ...... 
    getter-setter. 
    } 


This is my code: 
    public static String getClassAnnotationValue(Class classType, Class annotationType, String attributeName) { 
      String value = null; 

      Annotation annotation = classType.getAnnotation(annotationType); 
      if (annotation != null) { 
       try { 
        value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation); 
       } catch (Exception ex) { 
        ex.printStackTrace(); 
       } 
      } 

      return value; 
     } 


String columnName = getClassAnnotationValue(PROVINCE .class, Column.class, "name");  

通過這種方式,我只得到的ColumnName爲省。我無法獲得ColumnName。我該怎麼做?

+0

String columnName = getClassAnnotationValue(PROVINCE .class,Table.class,「name」); – 2014-10-09 10:44:14

回答

1

@Column註釋是在字段上定義的,而不是在類上定義的。所以,你必須從私有字段查詢註釋值:

String columnName = getAnnotationValue(PROVINCE.class.getDeclaredField("provinceCode"), Column.class, "name"); 

爲了能夠通過Field對象,以你的方法,改變你的classType參數的類型從ClassAnnotatedElement。然後,您可以傳遞類,字段,參數或方法:

public static String getAnnotationValue(AnnotatedElement element, Class annotationType, String attributeName) { 
    ... 
}