Spring之工具类

Spring之常用工具类

日常学习开发中,项目中经常需要用到各种工具类,而Spring框架中为我们提供了一些列工具,我们可以在不引用其他包的情况下,使用这些工具也能满足常规需求。

断言工具Assert

public static void testAssert() {
    // false将会抛出IllegalStateException异常
    Assert.state(false, "状态异常");
    // 自定义消息时,传递一个Supplier函数式接口
    Assert.state(false, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // false将抛出IllegalArgumentException异常
    Assert.isTrue(false, "非法参数");
    // 传递一个Supplier函数式接口
    Assert.isTrue(false, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 判断对象不为空,则抛异常IllegalArgumentException
    Object obj = new Object();
    Assert.isNull(obj, "对象不为空抛异常");
    Assert.isNull(obj, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 对象为空,则抛出异常IllegalArgumentException
    Assert.notNull(null, "空异常");
    Assert.notNull(null, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 字符串没有长度,则抛异常IllegalArgumentException
    // null, "" 抛异常
    // 有长度的空白串则不抛异常
    Assert.hasLength("", "字符串有长度");
    Assert.hasLength("", () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 字符串中没有非空字符,则抛异常IllegalArgumentException
    Assert.hasText(" s ", "字符串中包含非空字符");
    Assert.hasText(" s ", () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 第二个参数中的字符串包含在第一个参数中,则抛异常IllegalArgumentException
    Assert.doesNotContain("abc", "ab", "包含字符串抛异常");
    Assert.doesNotContain("abc", "ab", () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 数组为空,则抛异常IllegalArgumentException
    Assert.notEmpty(new Object[]{}, "空数组异常");
    Assert.notEmpty(new Object[]{}, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // Map为空,则抛异常IllegalArgumentException
    Assert.notEmpty(new HashMap<>(), "空map异常");
    Assert.notEmpty(new HashMap<>(), () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // Collection集合为空,则抛异常IllegalArgumentException
    Assert.notEmpty(new ArrayList<>(), "空集合异常");
    Assert.notEmpty(new ArrayList<>(), () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 数组中有null元素,抛异常
    // 集合中有null元素,也抛出异常
    Object[] array = new Object[]{1, null};
    Assert.noNullElements(array, "数组有null元素异常");
    Assert.noNullElements(array, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 第二个参数必须为第一个参数的对象实例类型,否则抛异常
    Assert.isInstanceOf(ArrayList.class, new HashMap<>(), "对象不为空指定类型异常");
    Assert.isInstanceOf(ArrayList.class, new HashMap<>(), () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

    // 第二个参数的类类型必须为第一个参数的类型的子类或实现类型
    Assert.isAssignable(List.class, ArrayList.class, "对象不为空指定的子类型异常");
    Assert.isAssignable(List.class, ArrayList.class, () -> {
        System.out.println("其他操作....");
        return "supplier info";
    });

}

对象工具ObjectUtils

public static void testObjectUtils() {
    // 是否是检查异常
    boolean isChecked = ObjectUtils.isCheckedException(new IOException());
    System.out.println(isChecked);

    //是否是指定类型中异常类的实例
    boolean isCompatible = ObjectUtils.isCompatibleWithThrowsClause(new RuntimeException(), RuntimeException.class);
    System.out.println(isCompatible);

    // 判断对象是否是数组类型
    boolean isArray = ObjectUtils.isArray(new int[]{});
    System.out.println(isArray);

    // 判断数组是否为空数组(null, 数组长度为0)
    boolean isEmpty = ObjectUtils.isEmpty(new int[]{});
    System.out.println(isEmpty);

    // 判断对象是否为空
    // Optional的值为空,字符串长度为0,数组长度为0
    // 集合元素为空,Map元素为空
    boolean empty = ObjectUtils.isEmpty(new Object());
    System.out.println(empty);

    // 获取Optional中的值,如果不是Optional,则直接返回值
    // 不支持嵌套多层的Optional
    Object obj = ObjectUtils.unwrapOptional(Optional.of("obj"));
    System.out.println(obj);

    // 判断数组中是否包含指定元素
    boolean ce = ObjectUtils.containsElement(new Integer[]{1, 2}, 3);
    System.out.println(ce);

    // 判断枚举数组中是否包含指定字符串,忽略大小写
    boolean enumConst = ObjectUtils.containsConstant(new Enum[]{}, "aaa");
    System.out.println(enumConst);
    // 不忽略大小写
    enumConst = ObjectUtils.containsConstant(new Enum[]{}, "aaa", true);
    System.out.println(enumConst);

    // 忽略大小写获取指定的枚举对象,不存在则抛异常
    Enum<?> anEnum = ObjectUtils.caseInsensitiveValueOf(new Enum[]{}, "aaa");
    System.out.println(anEnum);

    // 将元素添加到数组中,并返回一个新的数组
    // null也会添加进去
    String[] newStrArr = ObjectUtils.addObjectToArray(new String[]{}, "str");
    System.out.println(Arrays.toString(newStrArr));

    // 将对象转换为数组
    Object arr = new int[]{1, 2, 3};
    Object[] array = ObjectUtils.toObjectArray(arr);
    System.out.println(Arrays.toString(array));

    // 比较两个对象是否相等,数组中元素一致
    boolean equals = ObjectUtils.nullSafeEquals(new String[]{"a", "b"}, new String[]{"a", "b"});
    System.out.println(equals);
    
	// 其他请参考源码...

}

字符串工具StringUtils

字符串工具

public static void testStringUtils() {
    // 字符串长度是否大于0,包括空白字符
    boolean hasLength = StringUtils.hasLength("");
    System.out.println(hasLength);

    // 字符串是否包含非空白字符文本
    boolean hasText = StringUtils.hasText("   ");
    System.out.println(hasText);

    // 字符串是否包括空白字符
    boolean whitespace = StringUtils.containsWhitespace(" ");
    System.out.println(whitespace);

    // 去除前后空格,返回新的字符串
    String whitespace1 = StringUtils.trimWhitespace(" s s ");
    System.out.println(whitespace1);

    // 去除字符串中的所有空格,返回新的字符串
    whitespace1 = StringUtils.trimAllWhitespace(" s s ");
    System.out.println(whitespace1);

    // 去除字符串首部空格,返沪新的字符串
    whitespace1 = StringUtils.trimLeadingWhitespace(" s s ");
    System.out.println(whitespace1.length());

    // 去除尾部空格,返回新的字符串
    whitespace1 = StringUtils.trimTrailingWhitespace(" s s ");
    System.out.println(whitespace1);

    // 去除开头指定的字符
    String newStr = StringUtils.trimLeadingCharacter("aaabcdef", 'a');
    // bcdef
    System.out.println(newStr);

    // 去除尾部指定的字符
    newStr = StringUtils.trimTrailingCharacter("abcdefff", 'f');
    System.out.println(newStr);

    // 匹配单字符,字符串为单个字符,否则返回false
    boolean matchesChar = StringUtils.matchesCharacter("a", 'a');
    System.out.println(matchesChar);

    // 忽略大小写匹配字符串前缀
    boolean startsWith = StringUtils.startsWithIgnoreCase("abcdef", "Abc");
    System.out.println(startsWith);

    // 忽略大小写匹配字符串后缀
    boolean endWith = StringUtils.endsWithIgnoreCase("abcdef", "Def");
    System.out.println(endWith);

    // 指定索引位置,匹配字符串,不忽略大小写
    boolean substringMatch = StringUtils.substringMatch("abcdef", 1, "bcd");
    System.out.println(substringMatch);

    // 计算一个字符串中指定子串的出现次数
    int count = StringUtils.countOccurrencesOf("abcbcbc", "bc");
    System.out.println(count);

    // 字符串替换
    String replace = StringUtils.replace("abcdef", "abc", "ABC");
    System.out.println(replace);

    // 删除指定字符串
    String delete = StringUtils.delete("abcdef", "bcd");
    System.out.println(delete);

    // 删除字符串中的包含的任意字符
    String deleteAny = StringUtils.deleteAny("abcdef", "acdf");
    // 删除了 a c d f 字符
    System.out.println(deleteAny);

    // 加一对单引号
    String quote = StringUtils.quote("str");
    System.out.println(quote);

    // 如果是字符串,则添加单引号,否则不添加
    Object quoteObj = StringUtils.quoteIfString("str");
    System.out.println(quoteObj);

    // 截取以最后一个 . 字符的字符串
    String unqualify = StringUtils.unqualify("www.baidu.com");
    // com
    System.out.println(unqualify);

    // 截取指定的字符的最后一个字符串
    unqualify = StringUtils.unqualify("this:name", ':');
    // name
    System.out.println(unqualify);

    // 首字母大写
    String aThis = StringUtils.capitalize("this");
    System.out.println(aThis);

    // 首字母小写
    aThis = StringUtils.uncapitalize("This");
    System.out.println(aThis);

}

路径工具

public static void testPathStr() {
    String path = "D:/data/a.txt";
    // 获取文件路径中的文件名
    String filename = StringUtils.getFilename(path);
    System.out.println(filename);

    // 获取文件扩展名
    String extension = StringUtils.getFilenameExtension(path);
    System.out.println(extension);

    // 去除扩展名
    String stripExtension = StringUtils.stripFilenameExtension(path);
    System.out.println(stripExtension);

    // D:/data + /abc  --> D:/data/abc
    String relativePath = StringUtils.applyRelativePath(path, "/abc");
    System.out.println(relativePath);

    String cleanPath = StringUtils.cleanPath("D:\\data\\a.txt");
    System.out.println(cleanPath);

    // 比较路径是否相等
    boolean pathEquals = StringUtils.pathEquals(path, "D:\\data\\a.txt");
    System.out.println(pathEquals);

    // 解码uri
    StringUtils.uriDecode("https://www.baidu.com/", Charset.defaultCharset());

    Locale zhCn = StringUtils.parseLocale("zh_CN");
    System.out.println(zhCn);

    // 时区
    TimeZone timeZone = StringUtils.parseTimeZoneString("GMT+8");
    System.out.println(timeZone);

}

数组字符串工具

public static void testArrayStr() {
    List<String> list = Arrays.asList("a", "b");
    // Enumeration<String> 类型转数组
    // 集合转数组
    String[] array = StringUtils.toStringArray(list);
    System.out.println(Arrays.toString(array));

    // 数组合并
    String[] arrays = StringUtils.concatenateStringArrays(new String[]{"a"}, new String[]{"b"});
    System.out.println(Arrays.toString(arrays));

    // 数组排序
    String[] array1 = StringUtils.sortStringArray(new String[]{"b", "a"});
    System.out.println(Arrays.toString(array1));

    // 去除数组中的非空元素的前后空格
    String[] arrayElements = StringUtils.trimArrayElements(new String[]{" a ", " b "});
    System.out.println(Arrays.toString(arrayElements));

    // 去除数组中重复的字符串
    String[] strings = StringUtils.removeDuplicateStrings(new String[]{"aa", "aa"});
    System.out.println(Arrays.toString(strings));

    // 字符串第一个匹配的分隔符分隔
    // [www, baidu.com]
    String[] split = StringUtils.split("www.baidu.com", ".");
    System.out.println(Arrays.toString(split));

    // 字符串数组转换为properties对象
    Properties properties = StringUtils.splitArrayElementsIntoProperties(
            new String[]{"user.kk", "pwd.123456"}, "."
    );
    // {user=kk, pwd=123456}
    System.out.println(properties);

}

集合工具CollectionUtils

public static void testCollectionUtils() {

    // 判断Collection集合为空
    boolean empty = CollectionUtils.isEmpty(new ArrayList<>());
    System.out.println(empty);

    // 判断Map为空
    boolean mapEmpty = CollectionUtils.isEmpty(new HashMap<>());
    System.out.println(mapEmpty);

    // 创建HashMap,指定期望大小
    Map<String, Object> map = CollectionUtils.newHashMap(10);
    System.out.println(map);

    // 创建LinkedHashMap,指定期望大小
    map = CollectionUtils.newLinkedHashMap(10);
    System.out.println(map);

    // 对象转集合
    Object obj = new String[]{"aa", "bb"};
    List<?> list = CollectionUtils.arrayToList(obj);
    System.out.println(list);

    // 合并数组中的内容到集合中
    List<String> list1 = new ArrayList<>();
    CollectionUtils.mergeArrayIntoCollection(obj, list1);
    System.out.println(list1);

    // 合并properties中的元素到Map中
    Properties properties = new Properties();
    properties.setProperty("name", "kenewstar");
    CollectionUtils.mergePropertiesIntoMap(properties, map);
    System.out.println(map);

    // 判断迭代器中是否含有指定元素
    boolean contains = CollectionUtils.contains(list1.iterator(), "aa");
    System.out.println(contains);

    // 判断集合中是否含有指定的元素
    // 比较对象的地址是否相等
    boolean instance = CollectionUtils.containsInstance(list1, "aa");
    System.out.println(instance);

    // 判断第二个集合中是否有元素存在第一个集合中
    boolean containsAny = CollectionUtils.containsAny(list1, Collections.singletonList("aa"));
    System.out.println(containsAny);

    // 查找第二个集合中匹配第一个集合的第一个元素,并返回
    String firstMatch = CollectionUtils.findFirstMatch(list1, Collections.singletonList("aa"));
    System.out.println(firstMatch);

    // 查找指定集合中指定类型的实例
    String valueOfType = CollectionUtils.findValueOfType(list1, String.class);
    System.out.println(valueOfType);

    // 集合内容全部一样则为true
    boolean unique = CollectionUtils.hasUniqueObject(list1);
    System.out.println(unique);

    // 查找集合第一个元素
    // firstElement(@Nullable Set<T> set)
    // firstElement(@Nullable List<T> list)

    // 查找集合最后一个元素
    // lastElement(@Nullable Set<T> set)
    // lastElement(@Nullable List<T> list)


}

文件拷贝工具FileCopyUtils

public static void testFileCopyUtils() throws IOException {

    // 文件拷贝,将1.exe拷贝一份为2.exe在同一个目录下
    FileCopyUtils.copy(
            new File("C:\\data\\tmp\\1.exe"),
            new File("C:\\data\\tmp\\2.exe")
    );

    // 将字节数组拷贝到文件中
    String info = "文件拷贝工具";
    FileCopyUtils.copy(
            info.getBytes(StandardCharsets.UTF_8),
            new File("C:\\data\\tmp\\1.txt")
    );

    // 读取文件内容为字节数数组
    byte[] data = FileCopyUtils.copyToByteArray(new File("C:\\data\\tmp\\1.txt"));
    System.out.println(new String(data));

    // 输入流转换为输出流
    FileCopyUtils.copy(
            new FileInputStream("C:\\data\\tmp\\1.txt"),
            new FileOutputStream("C:\\data\\tmp\\2.txt")
    );

    // 字节数组转为输出流
    FileCopyUtils.copy(
            info.getBytes(StandardCharsets.UTF_8),
            new FileOutputStream("C:\\data\\tmp\\2.txt")
    );

    // 输入流返回字节数组
    byte[] array = FileCopyUtils.copyToByteArray(new FileInputStream("C:\\data\\tmp\\1.txt"));
    System.out.println(new String(array));

    // 文件字符流拷贝
    FileCopyUtils.copy(
            new FileReader("C:\\data\\tmp\\1.txt"),
            new FileWriter("C:\\data\\tmp\\2.txt")
    );

    // 字符串转为字符输出流
    FileCopyUtils.copy(info, new FileWriter("C:\\data\\tmp\\2.txt"));

    // 字符输入流转为字符串
    String str = FileCopyUtils.copyToString(new FileReader("C:\\data\\tmp\\1.txt"));
    System.out.println(str);

}

资源工具ResourceUtils

public static void testResourceUtils() throws Exception {
    // 是否是一个url
    boolean isUrl = ResourceUtils.isUrl("https://www.baidu.com");
    System.out.println(isUrl);
    isUrl = ResourceUtils.isUrl("classpath:spring.xml");
    System.out.println(isUrl);

    // 获取URL对象
    URL url = ResourceUtils.getURL("classpath:test.txt");
    System.out.println(url);

    // 获取文件对象
    File file = ResourceUtils.getFile("classpath:test.txt");
    System.out.println(file);

    // 读取本地文件资源
    file = ResourceUtils.getFile(new URL("file:\\c:\\data\\tmp\\1.txt"));
    System.out.println(file);

    URI uri = ResourceUtils.toURI("c:\\data\\tmp\\1.txt");
    System.out.println(uri);

}

IO流工具StreamUtils

public static void testStreamUtils() throws Exception {
    FileInputStream fis = new FileInputStream("c:/data/tmp/1.txt");
    // 文件输入流转换为字节数组
    byte[] data = StreamUtils.copyToByteArray(fis);
    System.out.println(new String(data));

    // 文件输入流转为字符串
    String info = StreamUtils.copyToString(fis, Charset.defaultCharset());
    System.out.println(info);

    // 字节数数组拷贝到输出流中
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamUtils.copy(data, os);

    // 输出流转换为字符串
    info = StreamUtils.copyToString(os, Charset.defaultCharset());
    System.out.println(info);
    
    // copy(String in, Charset charset, OutputStream out)
    
    // copy(InputStream in, OutputStream out)

    // copyRange(InputStream in, OutputStream out, long start, long end)
}

反射工具ReflectionUtils

private String myName;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MustMethod {

}

@MustMethod
public static void testReflectionUtils() throws Exception {
    RuntimeException exception = new RuntimeException("异常");

    // 用于处理反射异常对象,不显示使用throw关键字抛异常
    ReflectionUtils.handleReflectionException(exception);

    // 处理运行时异常,不显示使用throw关键字抛异常
    ReflectionUtils.rethrowRuntimeException(exception);

    // 重新抛出Exception异常
    ReflectionUtils.rethrowException(exception);

    InvocationTargetException excep = new InvocationTargetException(exception);
    // 处理目标方法调用异常
    ReflectionUtils.handleInvocationTargetException(excep);

    // 可添加构造方法的参数
    // accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
    // 设置第一个参数为目标类,第二个参数为构造方法的参数列表
    // 设置该构造方法为可反射访问
    ReflectionUtils.accessibleConstructor(TestReflectionUtils.class);

    // 设置指定的构造方法反射对象可访问
    // 设置指定的方法反射可访问
    // 设置指定的属性反射可访问
    ReflectionUtils.makeAccessible(TestReflectionUtils.class.getConstructor());

    // 查找指定类的方法
    // 第三个参数为方法的参数列表,可变参数
    ReflectionUtils.findMethod(TestReflectionUtils.class, "testReflectionUtils");

    // 查找指定类的属性,包括父类中的属性,但不包括Object类
    ReflectionUtils.findField(TestReflectionUtils.class, "myName");

    // 获取指定的方法对象
    Method myMethod = TestReflectionUtils.class.getDeclaredMethod("myMethod");
    // 反射调用该方法,返回对象为方法执行返回的对象
    // 第三个为可变参数,为方法执行的参数列表
    ReflectionUtils.invokeMethod(myMethod, TestReflectionUtils.class.newInstance());

    // 判断方法中声明的异常是否有该异常类型
    boolean declare =  ReflectionUtils.declaresException(myMethod, Exception.class);
    System.out.println(declare);

    // 获取当前类(不包括父类)所有的方法,对方法对象自定义实现回调机制
    ReflectionUtils.doWithLocalMethods(TestReflectionUtils.class, method -> {
        // 参数为Method对象
        System.out.println(method.getName());
    });

    // 获取指定类的所有方法,包括父类的所有方法,且包括Object类的方法
    ReflectionUtils.doWithMethods(TestReflectionUtils.class, method -> {
        // 参数为Method对象
        System.out.println(method.getName());
    });

    // 获取所有的方法,包括父类的方法
    // 指定方法过滤器,返回true则表示方法被MethodCallback回调器所调用
    ReflectionUtils.doWithMethods(TestReflectionUtils.class, method -> {
        System.out.println(method.getName());
    }, method -> method.isAnnotationPresent(MustMethod.class));

    // 获取所有方法包括父类的方法
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(TestReflectionUtils.class);
    System.out.println(Arrays.toString(methods));

    // 获取所有方法,不包括父类的方法
    methods = ReflectionUtils.getDeclaredMethods(TestReflectionUtils.class);
    System.out.println(Arrays.toString(methods));

    // 判断是否是equals方法
    boolean isEquals = ReflectionUtils.isEqualsMethod(
            TestReflectionUtils.class.getMethod("equals", Object.class)
    );
    System.out.println(isEquals);

    // 判断是否HashCode方法
    // boolean isHashCodeMethod(@Nullable Method method)
    // 判断是否是ToString方法
    // boolean isToStringMethod(@Nullable Method method)
    // 判断是否由Object类声明的方法
    // boolean isObjectMethod(@Nullable Method method)
    // 判断是否是Cglib方法
    // boolean isCglibRenamedMethod(Method renamedMethod)

    // 反射设置属性的值
    // setField(Field field, @Nullable Object target, @Nullable Object value)
    // 反射获取属性的值
    // Object getField(Field field, @Nullable Object target)

    // 获取指定类的所有属性,不包括父类,并调用属性回调器
    ReflectionUtils.doWithLocalFields(TestReflectionUtils.class, field -> {
        System.out.println(field.getName());
    });

    // 获取指定类的所有属性,包括父类,并调用属性回调器
    ReflectionUtils.doWithFields(TestReflectionUtils.class, field -> {
        System.out.println(field.getName());
    });

    // 获取所有属性,包括父类,通过属性过滤器筛选后,再调用属性回调器
    ReflectionUtils.doWithFields(TestReflectionUtils.class, field -> {
        System.out.println(field.getName());
    }, field -> field.getType().isAssignableFrom(String.class));

    // 拷贝src对象的属性值到dest对象的属性上,包括父类的属性,且对象的类型必须一致,或者父类型
    // shallowCopyFieldState(final Object src, final Object dest)
    
    // 判断属性是否是静态常量
    // boolean isPublicStaticFinal(Field field)

}

切面工具AopUtils

public static void testAopUtils() {
    // 是否是Aop代理对象
    boolean aopProxy = AopUtils.isAopProxy(new Object());
    System.out.println(aopProxy);

    // 是否是JDK动态代理对象
    aopProxy = AopUtils.isJdkDynamicProxy(new Object());
    System.out.println(aopProxy);

    // 是否是Cglib代理对象
    aopProxy = AopUtils.isCglibProxy(new Object());
    System.out.println(aopProxy);

    // 获取代理对象的目标类类型
    Class<?> targetClass = AopUtils.getTargetClass(new Object());
    System.out.println(targetClass);


}

AopContext

// 获取当前类的代理对象
Object proxy = AopContext.currentProxy();

小结

Spring框架中的工具类非常丰富,本文中只列举了日常开发中一些常用的工具,**org.springframework.util **所有工具类均在此包下,可自行查找。

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值