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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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);
}

}