标签:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface RevisionColumn { String value(); }
public class ResourceItem { private int id; private int revision; private ResourceItemStatus status; @RevisionColumn("节点") private String node; @RevisionColumn("是否物理隔离") private boolean physicalIsolation; @RevisionColumn("整机:单盘上限(%)") private int machineDiskLimit; //... }
public class FieldChangeInfo implements Serializable{ private String propertyName; private String propertyHeader; private Object from; private Object to; public FieldChangeInfo() { } public FieldChangeInfo(String propertyName, String propertyHeader, Object from, Object to) { this.propertyName = propertyName; this.propertyHeader = propertyHeader; this.from = from; this.to = to; } @Override public boolean equals(Object obj) { if (!(obj instanceof FieldChangeInfo)) return false; if (obj == this) return true; FieldChangeInfo rhs = (FieldChangeInfo) obj; return new EqualsBuilder(). append(propertyName, rhs.propertyName). append(propertyHeader, rhs.propertyHeader). append(from, rhs.from). append(to, rhs.to). isEquals(); } public String getPropertyName() { return propertyName; } public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getPropertyHeader() { return propertyHeader; } public void setPropertyHeader(String propertyHeader) { this.propertyHeader = propertyHeader; } public Object getFrom() { return from; } public void setFrom(Object from) { this.from = from; } public Object getTo() { return to; } public void setTo(Object to) { this.to = to; } }
public static List<FieldChangeInfo> getResourceItemFieldChangeInfo(ResourceItem originalItem, ResourceItem updatedItem) { try { List<FieldChangeInfo> fieldChangeInfos = new LinkedList<>(); for (Field field : ResourceItem.class.getDeclaredFields()) { RevisionColumn revisionColumn = field.getAnnotation(RevisionColumn.class); if (revisionColumn != null) { field.setAccessible(true); Object originalValue = field.get(originalItem); Object updatedValue = field.get(updatedItem); if (originalValue == null && updatedValue == null) continue; if (originalValue == null || !originalValue.equals(updatedValue)){ FieldChangeInfo fieldChangeInfo = new FieldChangeInfo(); fieldChangeInfo.setFrom(originalValue); fieldChangeInfo.setTo(updatedValue); fieldChangeInfo.setPropertyName(field.getName()); fieldChangeInfo.setPropertyHeader(revisionColumn.value()); fieldChangeInfos.add(fieldChangeInfo); } } } return fieldChangeInfos; } catch (IllegalAccessException e) { throw new RuntimeException("检测ResourceItem字段变更时出现异常"); } }
标签:
原文地址:http://www.cnblogs.com/gods/p/4202023.html