这个问题已经在这里有一个答案:
- 检索使用Java反射机制继承的属性名称/值 12个回答
我最近改变了我的方案了一点,所以我的课从超类继承,问题是它生成一个审计日志,使用Java反映,现在只能通过子类的字段循环我的比较方法,而不是超,是有没有办法让所有的字段? 或者我需要把它丢在超类.....?
继承人我下面的方法:
public static <T> String GenerateChangeLogForEntity(T old, T updated) {
String text = "";
try {
Field[] fields = old.getClass().getDeclaredFields();
if(fields != null) {
BaseController.getLogger().info("Z1 num fields:"+fields.length);
for (Field field : fields) {
if(field.isAnnotationPresent(Column.class)) {
String fieldName = field.getName();
BaseController.getLogger().info(field.getName());
if(field.isAnnotationPresent(Variation.class)) {
Variation v = field.getAnnotation(Variation.class);
fieldName = v.friendlyName();
}
field.setAccessible(true);
if(field.get(old) != null && field.get(updated) != null) {
if(!(field.get(old)).equals(field.get(updated))) {
text += "<p><span class=\"field-name\">"+fieldName+"</span> changed from: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(old))+"</strong> to: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(updated)) + "</strong></p>";
}
}
if(field.get(old) == null && field.get(updated) != null) {
text += "<p><span class=\"field-name\">"+fieldName+"</span> changed from: <strong>empty</strong> to: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(updated)) + "</strong></p>";
}
if(field.get(old) != null && field.get(updated) == null) {
text += "<p><span class=\"field-name\">"+fieldName+"</span> changed from: <strong>"+GetFriendlyFieldValueForChangeLog(field.get(updated))+"</strong> to <strong>empty</strong>" + "</p>";
}
field.setAccessible(false);
}
}
}
} catch(IllegalAccessException e) {}
return text;
}