SpringBoot—bean工具类封装

关注 wx:CodingTechWork

需求

  在Java开发代码中,经常会有一些对象Bean转换的需求,如下进行模板总结。

模板

public class BeansUtils {
    
    

    /**
     * Object to bean
     *
     * @param obj
     * @param t
     * @param <T>
     * @return
     */
    public static <T> T objToBean(Object obj, Class<T> t) {
    
    
        //判空
        if (null != obj) {
    
    
            //转jsonStr
            String jsonStr = JSONObject.toJSONString(obj);
            //json string对应bean
            return JSONObject.parseObject(jsonStr, t);
        }
        //返回null
        return null;
    }

    /**
     * 解析obj为string
     *
     * @param obj
     * @return
     */
    public static String objToString(Object obj) {
    
    
        if (null != obj) {
    
    
            return JSONObject.toJSON(obj).toString();
        }
        return null;
    }

    /**
     * 拷贝soruces list对象到target对象中
     *
     * @param sources
     * @param target
     * @param <S>
     * @param <T>
     * @return
     */
    public static <S, T> List<T> copyList(List<S> sources, Supplier<T> target) {
    
    
        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
    
    
            T t = target.get();
            BeanUtils.copyProperties(source, t);
            list.add(t);
        }
        return list;
    }

}

猜你喜欢

转载自blog.csdn.net/Andya_net/article/details/129936807