利用反射批量修改javabean的属性值

逆流者 2019年12月31日 152次浏览

直接上代码

public static void main(String[] args) throws IllegalAccessException {
        Employee employee = new Employee();
        System.out.println("employee before: " + employee);
        // 获取对象所有的实例域
        Field[] fields = employee.getClass().getDeclaredFields();
        // 获得访问私有实例域的权限
        AccessibleObject.setAccessible(fields, true);
        for (Field field : fields) {
            Class<?> type = field.getType();
            if ("String".equals(type.getSimpleName())) {
                Object obj = field.get(employee);
                if (obj != null) {
                    String str = obj.toString();
                    if ("Jerry".equals(str)) {
                        field.set(employee, "Tom");
                    }
                }

            }
        }
        System.out.println("employee after: " + employee);
    }
class Employee {

    private String name = "Jerry";
    private String age;

    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

打印结果:
employee before: Employee{name='Jerry', age='null'}
employee after: Employee{name='Tom', age='null'}