1. 对象String类型参数为undefined, 反射处理替换成空字符串""
import org.apache.curator.shaded.com.google.common.collect.Lists;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
/**
* 处理undefined
*
* @apiNote 2023-05-16
*/
public class UndefinedUtil {
/**
* 处理结果对象中的String类型的undefined - 替换未空字符串“” --- 处理单个对象使用
*
* @param responseTO 结果对象
*/
public static void dealUndefined(Object responseTO) {
try {
Class<?> accountClass = responseTO.getClass();
Field[] fields = accountClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
String fieldClassName = field.getGenericType().toString();
if ("class java.lang.String".equalsIgnoreCase(fieldClassName)) {
String methodName = getMethodName(field.getName());
// soaProxy内对象存在"SIGN_MSG"参数
if ("SIGN_MSG".equalsIgnoreCase(methodName)) {
continue;
}
Method classMethod = (Method)accountClass.getMethod(
"get" + methodName);
String stringValue = (String)classMethod.invoke(responseTO);
if ("undefined".equalsIgnoreCase(stringValue)) {
field.set(responseTO, StringUtil.EMPTY);
CommonLogUtil.logEs(LogLevelEnum.Info, UndefinedUtil.class, "dealUndefinedSetEmpty",
String.format("deal fieldName: %s, set value empty", field.getName()));
}
}
}
} catch (Exception e) {
CommonLogUtil.logEs(LogLevelEnum.Error, UndefinedUtil.class, "dealUndefinedException", JsonUtil.toJson(e));
}
}
/**
* 参数名称转首字母转大写
*
* @param filedName 参数名称
* @return 结果
*/
private static String getMethodName(String filedName) {
// soaProxy内对象存在"SIGN_MSG"参数
if ("SIGN_MSG".equalsIgnoreCase(filedName)) {
return filedName;
}
byte[] items = filedName.getBytes();
items[0] = (byte)((char)items[0] - 'a' + 'A');
return new String(items);
}
}
2. 反射会对性能有影响 - 转载:Java反射性能探讨_getdeclaredfield 性能_计缘FromZero的博客-优快云博客