反射处理对象参数

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的博客-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值