public class Demo2 {
private Integer id;
@MyAnnotation
private String name;
@MyAnnotation
private Integer age;
public String getName() {
return name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public static void main(String[] args) throws Exception {
Demo2 demo = new Demo2();
demo.setId(1);
demo.setName("小明");
demo.setAge(11);
Demo2 demo2 = new Demo2();
demo2.setId(1);
demo2.setName("小明");
demo2.setAge(13);
if(compareField(demo, demo2)){
System.out.println("属性值变化了。。。。。。");
}
}
public static Boolean compareField(Object account, Object oldAccount) throws Exception {
if(account ==null && oldAccount==null){
return Boolean.FALSE;
}
if(account!=null || oldAccount==null){
return Boolean.TRUE;
}
Class> clazz = account.getClass();
Class> clazz2 = oldAccount.getClass();
if(!clazz.equals(clazz2)){
throw new Exception("对象不是同一个,无法比对字段值");
}
Field[] fildArray = clazz.getDeclaredFields();
for (Field field : fildArray) {
if(field.isAnnotationPresent(MyAnnotation.class)){
field.setAccessible(true);
Object newField = field.get(account);
Field declaredField = clazz2.getDeclaredField(field.getName());
declaredField.setAccessible(true);
Object oldField = declaredField.get(oldAccount);
if(!(newField+"").equals(oldField+"")){
return Boolean.TRUE;
}
}
}
return Boolean.FALSE;
}
}
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}