/**
* 为指定对象的指定属性动态赋予指定值
*
* @param obj 指定对象
* @param fieldName 指定属性
* @param value 指定值
* @return obj 返回对象
*/
public static Object dynamicSetValue(Object obj, String fieldName, Object value) {
try {
// 取属性首字母转大写
String firstLetter = fieldName.substring(0, 1).toUpperCase();
// set方法名
String setMethodName = "set" + firstLetter + fieldName.substring(1);
// 获取属性
Field field = obj.getClass().getDeclaredField(fieldName);
// 获取set方法
Method setMethod = obj.getClass().getDeclaredMethod(setMethodName, field.getType());
// 通过set方法动态赋值
setMethod.invoke(obj, value);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 动态获取指定对象指定属性的值
*
* @param obj 指定对象
* @param fieldName 指定属性
* @return 属性值
*/
public static Object dynamicGetValue(Object obj, String fieldName) {
try {
// 取属性首字母转大写
String firstLetter = fieldName.substring(0, 1).toUpperCase();
// get方法名
String getMethodName = "get" + firstLetter + fieldName.substring(1);
// 获取get方法
Method getMethod = obj.getClass().getDeclaredMethod(getMethodName);
// 动态取值
return getMethod.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}