一星陨落,黯淡不了星空灿烂;一花凋零,荒芜不了整个春天。——巴尔扎克
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;
public class OptUtils {
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()); }
public static Object nullToNew(Object obj, Class cls) { try { return Optional.ofNullable(obj).orElse(cls.newInstance()); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; }
@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; }
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); }
}
|