当我们不知道传进来的对象有哪些属性并却还要赋值的时候,可以使用反射机制
class Test{
public static void main(String[] args) throws Exception {
// Student student = new Student("factory","北京",0);
// getValue(student);
Student student = new Student();
Map<String, Object> map = new HashMap<>();
map.put("name","胡图图");
map.put("address","翻斗家园");
map.put("status",1);
Student student1=(Student)setValue(student,map) ;
System.out.println(student1);
}
/**
*
* @param obj 传入的任意值
* @throws IllegalAccessException
*/
public static void getValue(Object obj) throws IllegalAccessException {
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
// 获取属性字段名
System.out.println(field.getName());
// 获取属性值
System.out.println(field.get(obj));
}
}
/**
*
* @param obj 传入的任意值
* @param map 集合
* @throws Exception
*/
public static Object setValue(Object obj, Map<String,Object> map) throws Exception {
Object newInstance=obj.getClass().getDeclaredConstructor().newInstance();
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (map.containsKey(field.getName())){
field.set(newInstance,map.get(field.getName()));
}
}
return newInstance;
}
}