一、判断是否为空
1. 判断字符串是否为空
org.springframework.util.StringUtils
if(StringUtils.isEmpty(Object str)){
...
}
StringUtils.isEmpty()传入的是Object,所以可以用来判断Long类型。
2. 判断集合是否为空
org.springframework.util.CollectionUtils
if(CollectionUtils.isEmpty(list/map)){
...
}
3. 判断对象是否为空
自己写工具类:
/**
* 检查对象是否为null
*
* @param obj 对象
* @return 是否为null
*/
public static boolean isNull(Object obj) {
//noinspection ConstantConditions
return null == obj || obj.equals(null);
}
/**
* 检查对象是否不为null
*
* @param obj 对象
* @return 是否为null
*/
public static boolean isNotNull(Object obj) {
//noinspection ConstantConditions
return null != obj && false == obj.equals(null);
}
二、Google Guava工具类
引入依赖
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
1. Preconditions.checkNotNull
import com.google.common.base.Preconditions;
Preconditions.checkNotNull(object);
优点:优雅地判空对象,并处理可能的NullPointerException异常
三、JavaBean和JsonStr互转
1. JavaBean对象转化为Json字符串
String json = JSON.toJSONString(Object object)
JSON类之toJSONString()方法,实现json对象转化为json字符串和javabean对象转化为json 字符串
2. Json字符串转化为JavaBean对象
JSON.parseObject(...)
Student stu1 = JSON.parseObject(jsonstr,new TypeReference<Student>(){});
Student stu2 = JSON.parseObject(jsonstr, Student.class);
3. object转JSONObject
JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
4. 获取JSONObject某个key对应的value
value为String类型:
String value = jsonObject.getString(key);
四、LocalDate工具类
1. 两个LocalDate类型日期计算时间差(天数)
private long dateBetween(LocalDate start,LocalDate end){
return ChronoUnit.DAYS.between(start, end);
// 或
return end.until(start, ChronoUnit.DAYS);
}