我有一个名为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作为PROVINCE。我无法获得ColumnName。我该怎么做?
答案 0 :(得分:1)
@Column
注释是在字段上定义的,而不是在类上定义的。因此,您必须从私有字段中查询注释值:
String columnName = getAnnotationValue(PROVINCE.class.getDeclaredField("provinceCode"), Column.class, "name");
为了能够将Field
个对象传递给您的方法,请将classType
参数的类型从Class
更改为AnnotatedElement
。然后你可以传递类,字段,参数或方法:
public static String getAnnotationValue(AnnotatedElement element, Class annotationType, String attributeName) {
...
}