实用避免空指针的工具类

2022-08-16 17:26:01 浏览数 (1)

一星陨落,黯淡不了星空灿烂;一花凋零,荒芜不了整个春天。——巴尔扎克

代码语言:javascript复制
package com.ruben.utils;


import com.ruben.pojo.User;
import org.thymeleaf.expression.Lists;
import sun.reflect.misc.ReflectUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @ClassName: OptUtils
 * @Date: 2020/11/25 0025 15:02
 * @Description: Optional工具类避免空指针
 * @Author: <achao1441470436@gmail.com>
 */
public class OptUtils {
    /**
     * @MethodName: toStripZeroString
     * @Description: 转换成去零字符串
     * @Date: 2020/11/25 0025 15:04
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [bigDecimal]
     * @returnValue: java.lang.String
     */
    public static String toStripZeroString(BigDecimal bigDecimal) {
        return Optional.ofNullable(bigDecimal).map(BigDecimal::stripTrailingZeros).map(BigDecimal::toPlainString).orElse("0");
    }

    public static String toStripZeroString(AtomicReference<BigDecimal> bigDecimalAtomicReference) {
        return toStripZeroString(bigDecimalAtomicReference.get());
    }

    /**
     * @MethodName: nullToNew
     * @Description: 如果为空则new一个,避免空指针
     * @Date: 2020/11/25 0025 15:19
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [obj, cls]
     * @returnValue: Object
     */
    public static Object nullToNew(Object obj, Class cls) {
        try {
            return Optional.ofNullable(obj).orElse(cls.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @MethodName: listGetFirst
     * @Description: list获取第一个
     * @Date: 2020/11/25 0025 15:54
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [list, cls]
     * @returnValue: java.lang.Object
     */
    @SuppressWarnings("unchecked")
    public static Object listGetFirst(List list, Class cls) {
        try {
            return Optional.ofNullable(list).orElse(new ArrayList()).stream().findFirst().orElse(cls.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @MethodName: main
     * @Description: 测试用例
     * @Date: 2020/11/25 0025 15:36
     * *
     * @author: <achao1441470436@gmail.com>
     * @param: [args]
     * @returnValue: void
     */
    public static void main(String[] args) {
        System.out.println(toStripZeroString(new BigDecimal("22.5")));
        User user = null;
        user = (User) nullToNew(user, User.class);
        System.out.println(user.getId());
        List<User> users = new ArrayList<>();
        System.out.println(users);
        Object o = listGetFirst(users, User.class);
        System.out.println(o);
    }

}

0 人点赞