1、通过反射获取对象的字段值
public static long getObjectValueByEnumField(String fieldName, Object object, Class<?> clazz) { try { //获取字段 Field field = clazz.getDeclaredField(HumpTranUtil.lineToHump(fieldName)); PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); //获取get方法 Method getMethod = pd.getReadMethod(); Object valueObj = ReflectionUtils.invokeMethod(getMethod, object); return valueObj == null ? 0 : Long.valueOf(valueObj.toString()); } catch (Exception e) { log.info("通过反射根据字段名称获取对应字段的值出错,fielaName={}", fieldName, e); return 0; } }
2、通过反射设置对象字段的值
public static void setObjValueByEnumField(Object object, Class<?> clazz, String fieldName, long value) { try { //获取字段 Field field = clazz.getDeclaredField(HumpTranUtil.lineToHump(fieldName)); field.setAccessible(true); field.set(object, value); field.setAccessible(false); } catch (Exception e) { log.info("通过反射根据字段名称设置对应字段的值出错,fieldName={}|value={}", fieldName, value, e); } }