public class Student {
private Integer id;
private String shortId;
private String name;
public Student(){
}
public Student(Integer id, String shortId, String name) {
this.id = id;
this.shortId = shortId;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getShortId() {
return shortId;
}
public void setShortId(String shortId) {
this.shortId = shortId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- getDeclaredField
包含public, protected, default范围权限的字段,不包含父类的字段
- getField
包含public权限的字段,包含父类的public权限的字段
public class TestSetObjectFieldValue {
public static void main(String[] args) throws Exception {
String[] fieldStrs = new String[]{"id", "name", "shortId"};
Class<Student> clazz = Student.class;
Student student = clazz.newInstance();
for (String fieldStr : fieldStrs) {
/**
* Returns an array containing {@code Method} objects reflecting all the
* declared methods of the class or interface represented by this {@code
* Class} object, including public, protected, default (package)
* access, and private methods, but excluding inherited methods.
*/
Field field = clazz.getDeclaredField(fieldStr);
/**
* Returns a Field object that reflects the specified public member field of the class or interface
* represented by this Class object.
*/
// clazz.getField(fieldStr);
// 注意
field.setAccessible(true);
if (field.getType().equals(Integer.class)) {
field.set(student, 111);
} else {
field.set(student, "111");
}
}
System.out.println(JSON.toJSONString(student));
}
}
网友评论