Java reflection mechanism to solve the problem of data transfer is empty

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ng_xiaohe/article/details/102738586

Small two methods for solving BeanUtils.copyProperties (x, y); problem is empty source object

1. Entity annotation database field to the Map Key, is required for non-null data package Value
@Override
public Map <String, Object> setNodeParamItems (DispatchInfoItem dispatchInfoItem) throws a NoSuchMethodException, a InvocationTargetException, IllegalAccessException {
Map <String, Object> = Map the HashMap new new <> ();
dispatchInfo dispatchInfo new new dispatchInfo = ();
IF (null = dispatchInfoItem!) {
BeanUtils.copyProperties (dispatchInfoItem, dispatchInfo);
}
Method, [] = dispatchInfo.getClass Methods () 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.根据值进行实际的操作

Guess you like

Origin blog.csdn.net/ng_xiaohe/article/details/102738586