java中如何通过Class获取类的属性、方法、注释

时间:2024-09-03 11:04:50

public static String getPKName(Class clazz) {
Field[] fields = clazz.getDeclaredFields();
for (Field f : fields) {
Annotation[] annotations = f.getAnnotations();
if (annotations.length <= 0) {
String name = f.getName();
String setMethodName = "get" + org.apache.commons.lang.StringUtils.left(name, 1).toUpperCase() + org.apache.commons.lang.StringUtils.substring(name, 1);
try {
Method method = clazz.getDeclaredMethod(setMethodName);
annotations = method.getAnnotations();
} catch (Exception e) {
e.printStackTrace();
}
}
for (Annotation anno : annotations) {
if (anno.toString().contains("@javax.persistence.Id()"))
return f.getName();
}
}
return null;

相关文章