简介
本文介绍Spring(SpringBoot)中的工具类。Spring工具类足够使用了,实际开发中要首选Spring自带的工具,实在没有才考虑第三方的。
断言(Assert)
断言是一个逻辑判断,用于检查不应该发生的情况。
对象、字符串、集合、注解等
对象工具(ObjectUtils)
字符串工具(StringUtils)
集合工具(CollectionUtils)
MultiValueMap(一个key对应多个value)
AnnotationUtils
AnnotatedElementUtils
ClassUtils
spring的org.springframework.util包下的ClassUtils类
// 获取对象的所有接口
Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(new User());
// 获取某个类的包名
String packageName = ClassUtils.getPackageName(User.class);
// 判断某个类是否内部类
System.out.println(ClassUtils.isInnerClass(User.class));
// 判断对象是否代理对象
System.out.println(ClassUtils.isCglibProxy(new User()));
流、文件、资源
StreamUtils
输入
void copy(byte[] in, OutputStream out)
int copy(InputStream in, OutputStream out)
void copy(String in, Charset charset, OutputStream out)
long copyRange(InputStream in, OutputStream out, long start, long end)
输出
byte[] copyToByteArray(InputStream in)
String copyToString(InputStream in, Charset charset)
// 舍弃输入流中的内容
int drain(InputStream in)
FileCopyUtils
输入
// 从文件中读入到字节数组中
byte[] copyToByteArray(File in)
// 从输入流中读入到字节数组中
byte[] copyToByteArray(InputStream in)
// 从输入流中读入到字符串中
String copyToString(Reader in)
输出
// 从字节数组到文件
void copy(byte[] in, File out)
// 从文件到文件
int copy(File in, File out)
// 从字节数组到输出流
void copy(byte[] in, OutputStream out) // 从输入流到输出流
int copy(InputStream in, OutputStream out) // 从输入流到输出流
int copy(Reader in, Writer out)
// 从字符串到输出流
void copy(String in, Writer out)
ResourceUtils
注意:public static File getFile(String resourceLocation)是读不到JAR包内resources路径下的文件的,只能读到IDE开发环境下未打成JAR包的文件。
ClassPathResource
反射
ReflectionUtils
ReflectUtils
AOP
AopUtils
编解码、字符编码
Base64Utils
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();
}
DigestUtils(加密)
对数据进行加密处理,可以使用org.springframework.util.DigestUtils。遗憾的是,只支持md5。
// md5加密
String md5Hex = DigestUtils.md5DigestAsHex("shawn222".getBytes());
System.out.println(md5Hex);
// 输出:93d7992104ddf8c5cf8a86e9e3f762fe
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);
其他
HttpStatus
org.springframework.http包下的HttpStatus枚举,已经把常用的http返回码给我们定义好了,直接拿来用就可以了。