相同对象比较属性值是否相同 有更新!

Published on with 256 views

需求场景:修改表单,提交保存时,要求判断修改了哪些字段,利用java反射轻松解决


首先我们创建一个实体类,生成get,set及构造方法

public class Student {

	private String name; // 姓名
	private Integer age; // 年龄
	private String sex; // 性别
	private Integer number; // 学号

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Integer getNumber() {
		return number;
	}

	public void setNumber(Integer number) {
		this.number = number;
	}

	public Student() {
		super();
	}	

	public Student(String name, Integer age, String sex, Integer number) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.number = number;
	}

}

新建一个测试类

package utils;


import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;

import model.Student;

public class CompareFieldsValue {
	
        // 相同对象比较属性值是否相同
	@Test
	public void compareFieldsValueTest() {
		Student student1 = new Student("张三", 18, "男", 25);
		Student student2 = new Student("李四", 18, "男", 26);
		List<String> list = compareFieldsValueTest(student1 , student2);
		System.out.println(StringUtils.join(list, ","));
	}
	
	
	public List<String> compareFieldsValueTest(Object obj1 , Object obj2) {
		List<String> list = new ArrayList<>();
		try {
			Class<? extends Object> class1 = obj1.getClass();
			Class<? extends Object> class2 = obj1.getClass();
			Field[] declaredFields1 = class1.getDeclaredFields(); // 获取所有字段
			for (Field field : declaredFields1) {
				field.setAccessible(true);
				String name = field.getName(); //字段名称
				// 获取字段名字的get方法名
				String fieldGetMethodName = getFieldGetMethodName(name); 
				//获取方法
				Method method = class1.getMethod(fieldGetMethodName, new Class<?>[] {});
				Method method2 = class2.getMethod(fieldGetMethodName, new Class<?>[] {});
				Object invoke = method.invoke(obj1, new Class<?>[] {});// 得到方法的执行结果
				Object invoke2 = method2.invoke(obj2, new Class<?>[] {});
				if(!StringUtils.equals(invoke.toString(), invoke2.toString())) {
					list.add(name);
				}
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null ;
	}
	
	/**
	 * @Description:获取字段名字的get方法名 就是将首字母大写
	 * @author: HeZhuxing
	 */
	public String getFieldGetMethodName(String fieldName) {
		return "get"+fieldName.substring(0, 1).toUpperCase()+fieldName.substring(1, fieldName.length());
	}
}

执行单元测试 得到的字段值结果如下

字段值不同的名称为:name,number

分享一首歌

回复