工具类
工具类
1.Collections
java.util包下的Collections类,该类主要用于操作集合或者返回集合
1.排序
2.获取最大或最小值
3.转换线程安全集合
4.返回空集合
5.二分查找
6.转换成不可修改集合
2.CollectionUtils
目前比较主流的是spring的org.springframework.util包下的CollectionUtils工具类
apache的org.apache.commons.collections包下的CollectionUtils工具类
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
推荐使用apache的包下的CollectionUtils工具类,因为它的工具更多更全面
1.集合判空
2.对两个集合进行操作
3.Lists
如果你引入com.google.guava的pom文件,会获得很多好用的小工具。这里推荐一款com.google.common.collect包下的集合工具:Lists
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
1.创建空集合
List<Integer> list = Lists.newArrayList();
2.快速初始化集合
List<Integer> list = Lists.newArrayList(1, 2, 3);
3.笛卡尔积
如果你想将两个集合做笛卡尔积,Lists的cartesianProduct方法可以帮你实现:
List<Integer> list1 = Lists.newArrayList(1, 2, 3);
List<Integer> list2 = Lists.newArrayList(4,5);
List<List<Integer>> productList = Lists.cartesianProduct(list1,list2);
System.out.println(productList);
结果
[[1, 4], [1, 5], [2, 4], [2, 5], [3, 4], [3, 5]]
4.分页
如果你想将一个大集合分成若干个小集合,可以使用Lists的partition方法
List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
List<List<Integer>> partitionList = Lists.partition(list, 2);
System.out.println(partitionList);
结果
[[1, 2], [3, 4], [5]]
5.流处理
如果我们想把某个集合转换成另外一个接口,可以使用Lists的transform方法。
List<String> list = Lists.newArrayList("a","b","c");
List<String> transformList = Lists.transform(list, x -> x.toUpperCase());
System.out.println(transformList);
转换为大写
6.颠倒顺序
Lists的有颠倒顺序的方法reverse。
List<Integer> list = Lists.newArrayList(3, 1, 2);
List<Integer> reverseList = Lists.reverse(list);
System.out.println(reverseList);
结果
[2, 1, 3]
4. Objects
在jdk7之后,提供了Objects工具类,我们可以通过它操作对象
1.对象判空
在java中万事万物皆对象,对象的判空可以说无处不在。Objects的isNull方法判断对象是否为空,而nonNull方法判断对象是否不为空。
2.对象为空抛异常
如果我们想在对象为空时,抛出空指针异常,可以使用Objects的requireNonNull方法
Integer integer1 = new Integer(128);
Objects.requireNonNull(integer1);
Objects.requireNonNull(integer1, "参数不能为空");
Objects.requireNonNull(integer1, () -> "参数不能为空");
3.判断两个对象是否相等
我们经常需要判断两个对象是否相等,Objects给我们提供了equals方法,能非常方便的
Integer integer1 = new Integer(1);
Integer integer2 = new Integer(1);
System.out.println(Objects.equals(integer1, integer2));
执行结果:
true
但使用这个方法有坑,比如例子改成
Integer integer1 = new Integer(1);
Long integer2 = new Long(1);
System.out.println(Objects.equals(integer1, integer2));
false
4.获取对象的hashCode
5.BooleanUtils
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
1.判断true或false
如果你想判断某个参数的值是true或false,可以直接使用isTrue或isFalse方法。
2.判断不为true或不为false
有时候,需要判断某个参数不为true,即是null或者false。或者判断不为false,即是null或者true。
可以使用isNotTrue或isNotFalse
3. 转换成数字
如果你想将true转换成数字1,false转换成数字0,可以使用toInteger方法
4.Boolean转换成布尔值
我们有时候需要将包装类Boolean对象,转换成原始的boolean对象,可以使用toBoolean方法。
6.StringUtils
org.apache.commons.lang3包下的StringUtils工具类,给我们提供了非常丰富的选择。
1.字符串判空
其实空字符串,不只是null一种,还有""," ","null"等等,多种情况。
StringUtils给我们提供了多个判空的静态方法,例如:
String str1 = null;
String str2 = "";
String str3 = " ";
String str4 = "abc";
System.out.println(StringUtils.isEmpty(str1));
System.out.println(StringUtils.isEmpty(str2));
System.out.println(StringUtils.isEmpty(str3));
System.out.println(StringUtils.isEmpty(str4));
System.out.println("=====");
System.out.println(StringUtils.isNotEmpty(str1));
System.out.println(StringUtils.isNotEmpty(str2));
System.out.println(StringUtils.isNotEmpty(str3));
System.out.println(StringUtils.isNotEmpty(str4));
System.out.println("=====");
System.out.println(StringUtils.isBlank(str1));
System.out.println(StringUtils.isBlank(str2));
System.out.println(StringUtils.isBlank(str3));
System.out.println(StringUtils.isBlank(str4));
System.out.println("=====");
System.out.println(StringUtils.isNotBlank(str1));
System.out.println(StringUtils.isNotBlank(str2));
System.out.println(StringUtils.isNotBlank(str3));
System.out.println(StringUtils.isNotBlank(str4));
执行结果:
true
true
false
false
=====
false
false
true
true
=====
true
true
true
false
=====
false
false
false
true
优先推荐使用isBlank和isNotBlank方法,因为它会把" "也考虑进去。
2.分隔字符串
分隔字符串是常见需求,如果直接使用String类的split方法,就可能会出现空指针异常。
String str1 = null;
System.out.println(StringUtils.split(str1,","));
System.out.println(str1.split(","));
执行结果
null
Exception in thread "main" java.lang.NullPointerException
at com.sue.jump.service.test1.UtilTest.main(UtilTest.java:21)
3.判断是否纯数字
给定一个字符串,判断它是否为纯数字,可以使用isNumeric方法。
String str1 = "123";
String str2 = "123q";
String str3 = "0.33";
System.out.println(StringUtils.isNumeric(str1));
System.out.println(StringUtils.isNumeric(str2));
System.out.println(StringUtils.isNumeric(str3));
执行结果:
true
false
false
4.将集合拼接成字符串
有时候,我们需要将某个集合的内容,拼接成一个字符串,然后输出,这时可以使用join方法。
List<String> list = Lists.newArrayList("a", "b", "c");
List<Integer> list2 = Lists.newArrayList(1, 2, 3);
System.out.println(StringUtils.join(list, ","));
System.out.println(StringUtils.join(list2, " "));
执行结果:
a,b,c
1 2 3
7.Assert
其实spring给我们提供了Assert类,它表示断言。
1.断言参数是否为空
断言参数是否空,如果不满足条件,则直接抛异常。
String str = null;
Assert.isNull(str, "str必须为空");
Assert.isNull(str, () -> "str必须为空");
Assert.notNull(str, "str不能为空");
如果不满足条件就会抛出IllegalArgumentException异常。
2.断言集合是否为空
断言集合是否空,如果不满足条件,则直接抛异常。
List<String> list = null;
Map<String, String> map = null;
Assert.notEmpty(list, "list不能为空");
Assert.notEmpty(list, () -> "list不能为空");
Assert.notEmpty(map, "map不能为空");
如果不满足条件就会抛出IllegalArgumentException异常。
3.断言条件是否为空
断言是否满足某个条件,如果不满足条件,则直接抛异常。
List<String> list = null;
Assert.isTrue(CollectionUtils.isNotEmpty(list), "list不能为空");
Assert.isTrue(CollectionUtils.isNotEmpty(list), () -> "list不能为空");
8.IOUtils
org.apache.commons.io包下的IOUtils类,会节省大量的时间。
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
1.读取文件
如果你想将某个txt文件中的数据,读取到字符串当中,可以使用IOUtils类的toString方法。
String str = IOUtils.toString(new FileInputStream("/temp/a.txt"), StandardCharsets.UTF_8);
System.out.println(str);
2.写入文件
如果你想将某个字符串的内容,写入到指定文件当中,可以使用IOUtils类的write方法。
String str = "abcde";
IOUtils.write(str, new FileOutputStream("/temp/b.tx"), StandardCharsets.UTF_8);
3.文件拷贝
如果你想将某个文件中的所有内容,都拷贝到另一个文件当中,可以使用IOUtils类的copy方法。
IOUtils.copy(new FileInputStream("/temp/a.txt"), new FileOutputStream("/temp/b.txt"));
4.读取文件内容到字节数组
如果你想将某个文件中的内容,读取字节数组中,可以使用IOUtils类的toByteArray方法。
byte[] bytes = IOUtils.toByteArray(new FileInputStream("/temp/a.txt"));
9.MDC
DC是org.slf4j包下的一个类,它的全称是Mapped Diagnostic Context,我们可以认为它是一个线程安全的存放诊断日志的容器。
MDC的底层是用了ThreadLocal来保存数据的。
我们可以用它传递参数。
10.ClassUtils
spring的org.springframework.util包下的ClassUtils类
1.获取对象的所有接口
如果你想获取某个对象的所有接口,可以使用ClassUtils的getAllInterfaces方法。
Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(new User());
2. 获取某个类的包名
如果你想获取某个类的包名,可以使用ClassUtils的getPackageName方法。
String packageName = ClassUtils.getPackageName(User.class);
System.out.println(packageName);
3.判断某个类是否内部类
如果你想判断某个类是否内部类,可以使用ClassUtils的isInnerClass方法。
System.out.println(ClassUtils.isInnerClass(User.class));
4.判断对象是否代理对象
如果你想判断对象是否代理对象,可以使用ClassUtils的isCglibProxy方法。
System.out.println(ClassUtils.isCglibProxy(new User()));
11.BeanUtils
spring给我们提供了一个JavaBean的工具类,它在org.springframework.beans包下面,它的名字叫做:BeanUtils。
1. 拷贝对象的属性
曾几何时,你有没有这样的需求:把某个对象中的所有属性,都拷贝到另外一个对象中。这时就能使用BeanUtils的copyProperties方法。
User user1 = new User();
user1.setId(1L);
user1.setName("苏三说技术");
user1.setAddress("成都");
User user2 = new User();
BeanUtils.copyProperties(user1, user2);
System.out.println(user2);
2.实例化某个类
如果你想通过反射实例化一个类的对象,可以使用BeanUtils的instantiateClass方法。
User user = BeanUtils.instantiateClass(User.class);
System.out.println(user);
3.获取指定类的指定方法
如果你想获取某个类的指定方法,可以使用BeanUtils的findDeclaredMethod方法。
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
System.out.println(declaredMethod.getName());
4.获取指定方法的参数
如果你想获取某个方法的参数,可以使用BeanUtils的findPropertyForMethod方法。
Method declaredMethod = BeanUtils.findDeclaredMethod(User.class, "getId");
PropertyDescriptor propertyForMethod = BeanUtils.findPropertyForMethod(declaredMethod);
System.out.println(propertyForMethod.getName());
12.ReflectionUtils
spring给我们提供了一个ReflectionUtils工具,它在org.springframework.util包下面。
1.获取方法
如果你想获取某个类的某个方法,可以使用ReflectionUtils类的findMethod方法。
Method method = ReflectionUtils.findMethod(User.class, "getId");
2获取字段
如果你想获取某个类的某个字段,可以使用ReflectionUtils类的findField方法。
Field field = ReflectionUtils.findField(User.class, "id");
3.执行方法
如果你想通过反射调用某个方法,传递参数,可以使用ReflectionUtils类的invokeMethod方法。
ReflectionUtils.invokeMethod(method, springContextsUtil.getBean(beanName), param);
4.判断字段是否常量
如果你想判断某个字段是否常量,可以使用ReflectionUtils类的isPublicStaticFinal方法。
Field field = ReflectionUtils.findField(User.class, "id");
System.out.println(ReflectionUtils.isPublicStaticFinal(field));
5.判断是否equals方法
如果你想判断某个方法是否equals方法,可以使用ReflectionUtils类的isEqualsMethod方法。
Method method = ReflectionUtils.findMethod(User.class, "getId");
System.out.println(ReflectionUtils.isEqualsMethod(method));
13.Base64Utils
有时候,为了安全考虑,需要将参数只用base64编码。这时就能直接使用org.springframework.util包下的Base64Utils工具类。它里面包含:encode和decode方法,用于对数据进行加密和解密。
String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("加密后:" + encode);
try {
String decode = new String(Base64Utils.decode(encode.getBytes()), "utf8");
System.out.println("解密后:" + decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
加密后:YWJj
解密后:abc
14.StandardCharsets
我们在做字符转换的时候,经常需要指定字符编码,比如:UTF-8、ISO-8859-1等等。
这时就可以直接使用java.nio.charset包下的StandardCharsets类中静态变量。
String str = "abc";
String encode = new String(Base64Utils.encode(str.getBytes()));
System.out.println("加密后:" + encode);
String decode = new String(Base64Utils.decode(encode.getBytes())
, StandardCharsets.UTF_8);
System.out.println("解密后:" + decode);
15.DigestUtils
有时候,我们需要对数据进行加密处理,比如:md5或sha256。可以使用apache的org.apache.commons.codec.digest包下的DigestUtils类。
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
1.md5加密
如果你想对数据进行md5加密,可以使用DigestUtils的md5Hex方法。
String md5Hex = DigestUtils.md5Hex("苏三说技术");
System.out.println(md5Hex);
2.sha256加密
如果你想对数据进行sha256加密,可以使用DigestUtils的sha256Hex方法。
String md5Hex = DigestUtils.sha256Hex("苏三说技术");
System.out.println(md5Hex);
16.SerializationUtils
有时候,我们需要把数据进行序列化和反序列化处理。传统的做法是某个类实现Serializable接口,然后重新它的writeObject和readObject方法。
但如果使用org.springframework.util包下的SerializationUtils工具类,能更轻松实现序列化和反序列化功能。
Map<String, String> map = Maps.newHashMap();
map.put("a", "1");
map.put("b", "2");
map.put("c", "3");
byte[] serialize = SerializationUtils.serialize(map);
Object deserialize = SerializationUtils.deserialize(serialize);
System.out.println(deserialize);
17. HttpStatus
很多时候,我们会在代码中定义http的返回码,比如:接口正常返回200,异常返回500,接口找不到返回404,接口不可用返回502等。
其实org.springframework.http包下的HttpStatus枚举,或者org.apache.http包下的HttpStatus接口,已经把常用的http返回码给我们定义好了,直接拿来用就可以了,真的不用再重复定义了。
18.guava
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>