Java反射机制解决数据传值为空的问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/ng_xiaohe/article/details/102738586

两个小方法,用于解决BeanUtils.copyProperties(x, y);中源对象的值为空问题

1.通过实体注解数据库字段为Map的Key,需要的非空值为Value封装数据
@Override
public Map<String, Object> setNodeParamItems(DispatchInfoItem dispatchInfoItem) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Map<String, Object> map = new HashMap<>();
DispatchInfo dispatchInfo = new DispatchInfo();
if (null != dispatchInfoItem) {
BeanUtils.copyProperties(dispatchInfoItem, dispatchInfo);
}
Method[] methods = dispatchInfo.getClass().getDeclaredMethods();
if (methods != null) {
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith(“get”)) {
Column column = dispatchInfo.getClass().getDeclaredMethod(methodName).getAnnotation(Column.class);
Object value = method.invoke(dispatchInfo);
if (null != column && StringUtils.isNotBlank(StringHelper.getString(value))) {
map.put(column.name(), value);
}
}
}
}
return map;
}
2. 根据获取的值注入;
public void getMethods(DispatchInfo dispatchInfo, Map<String, Object> map) throws Exception {
//获取方法上的注解值
Method[] methods = dispatchInfo.getClass().getDeclaredMethods();
if (methods != null) {
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith(“get”)) {
Column column = dispatchInfo.getClass().getDeclaredMethod(methodName).getAnnotation(Column.class);
if (column != null) {
String setMethodName = methodName.replaceFirst("(get)", “set”);
Method setMethod = dispatchInfo.getClass().getMethod(setMethodName, method.getReturnType());
;
if (null != map.get(column.name())) {
setMethod.invoke(dispatchInfo, map.get(column.name()));
}
}
}
}
}
}
3.根据值进行实际的操作

猜你喜欢

转载自blog.csdn.net/ng_xiaohe/article/details/102738586