常用的校验API

常用的校验API

Assert

org.springframework.util.Assert

用途:可用在controller校验参数上,并由全局异常捕获器捕捉IllegalArgumentException,返回友好提示

缺点:不能返回业务的异常码,不过可参考改写成适合自己的

/**
 * org.springframework.util.Assert的用法
 * 简单,翻看源码就明白了
 *
 * @author : lyn
 * @date : 2022-08-17 22:13
 */
public class AssertTest {
    @Test
    public void test1(){
        Assert.isNull("","为null");
        //java.lang.IllegalArgumentException: 为null
        //如果第一个参数不满足,就抛出IllegalArgumentException,异常信息为第二个参数
    }
}

部分源码

    public static void isNull(@Nullable Object object, String message) {
        if (object != null) {
            throw new IllegalArgumentException(message);
        }
    }

StringUtils

org.springframework.util.StringUtils

方法介绍

StringUtils常用方法 描述
boolean isEmpty(Object str) 判断字符串是否为空,如果为nul或者""则返回true,否则返回false
boolean hasLength(CharSequence str) 判断字符串是否有长度,字符串不等于null且长度大于0,则为true,否则返回false
boolean hasText(CharSequence str) 如果字符序列中有一个不是空白"",返回true,否则返回false(空格字符串也是)
boolean containsWhitespace(CharSequence str) 判断字符序列是否包含空白,有一个字符是空白,返回true,否则返回false
String trimWhitespace(String str) 用于去除字符串前后的空白
String trimAllWhitespace(String str) 去除字符串所有空白
String trimLeadingWhitespace(String str) 去除字符串左边的空白字符
String trimTrailingWhitespace(String str) 去除字符串右边边的空白字符
trimLeadingCharacter(String str, char leadingCharacter) 删除字符串左边为leadingCharacter的字符
String trimTrailingCharacter(String str, char trailingCharacter) 删除字符串右边为trailingCharacter的字符
startsWithIgnoreCase(String str, String prefix) 忽略大小写,然后判断字符串是否已prefix前缀开始
boolean endsWithIgnoreCase(String str, String suffix) 忽略大小写,判断源字符串是否以suffix结尾
String getFilename(String path) 获取文件名
String getFilenameExtension(String path) 获取文件扩展名
String stripFilenameExtension(String path) 去除文件扩展名
String replace(String inString, String oldPattern, String newPattern) 替换字符串,参1:字符串,参2:需要替换的字符串,参3:用来替换的字符串
String delete(String inString, String pattern) 从给定的字符串中删除所有匹配的字符
String deleteAny(String inString, String charsToDelete) 删除所有指定字符

测试代码

import org.junit.Test;
import org.springframework.util.StringUtils;

/**
 * org.springframework.util.StringUtils用法测试
 *
 * @author : lyn
 * @date : 2022-08-17 22:47
 */
public class StringUtilsTest {
    /**
     * 判断字符串是否为空," "也不符合
     */
    @Test
    public void test1(){
        System.out.println(StringUtils.hasText(" "));
        //false
    }

    /**
     * 去除空白字符
     */
    @Test
    public void test2(){
        String str=" 122 4645 ";
        System.out.println(StringUtils.trimWhitespace(str));
        //122 4645
        System.out.println(StringUtils.trimAllWhitespace(str));
        //1224645
        System.out.println(StringUtils.trimLeadingWhitespace(str));
        //122 4645
        System.out.println(StringUtils.trimTrailingWhitespace(str));
        // 122 4645
    }
    @Test
    public void test3(){
        String str="88789811";
        System.out.println(StringUtils.trimTrailingCharacter("88789811",'1'));
        //887898
        System.out.println(StringUtils.trimLeadingCharacter("88789811",'8'));
        //789811
    }
    @Test
    public void test4(){
        System.out.println(StringUtils.startsWithIgnoreCase("WHO ARE YOU ","who"));
        //true
        System.out.println(StringUtils.endsWithIgnoreCase("WHO ARE YOU ","YoU "));
        //true
        System.out.println(StringUtils.getFilename("c://dd//who.jpg"));
        //who.jpg
        System.out.println(StringUtils.getFilenameExtension("c://dd//who.jpg"));
        //jpg
        System.out.println(StringUtils.stripFilenameExtension("c://dd//who.jpg"));
        //c://dd//who
        System.out.println(StringUtils.deleteAny("who ** are ** you ","*"));
        //who  are  you
    }
}

CollectionUtils

org.springframework.util.CollectionUtils

方法介绍

 // 判断 List/Set 是否为空
boolean isEmpty(Collection<?> collection)
// 判断 Map 是否为空
boolean isEmpty(Map<?,?> map)
// 判断 List/Set 中是否包含某个对象
boolean containsInstance(Collection<?> collection, Object element)
// 以迭代器的方式,判断 List/Set 中是否包含某个对象
boolean contains(Iterator<?> iterator, Object element)
// 判断两个集合是否有交集
boolean containsAny(Collection<?> source, Collection<?> candidates)
// 判断 集合中的每个元素是否唯一,即 集合中中不存在重复元素
boolean hasUniqueObject(Collection<?> collection)
// 将 Array 中的元素都添加到 List/Set 中
<E> void mergeArrayIntoCollection(Object array, Collection<E> collection)  
// 将 Properties 中的键值对都添加到 Map 中
<K,V> void mergePropertiesIntoMap(Properties props, Map<K,V> map)
// 返回 List 中最后一个元素
<T> T lastElement(List<T> list)  
// 返回 Set 中最后一个元素
<T> T lastElement(Set<T> set) 
// 返回参数 candidates 中第一个存在于参数 source 中的元素
<E> E findFirstMatch(Collection<?> source, Collection<E> candidates)
// 返回 List/Set 中指定类型的元素。指定类型的元素只能有一个,如果是多个的话返回null
<T> T findValueOfType(Collection<?> collection, Class<T> type)
// 返回 List/Set 中指定类型的元素。如果第一种类型未找到,则查找第二种类型,以此类推
Object findValueOfType(Collection<?> collection, Class<?>[] types)
// 返回 List/Set 中元素的类型,如果集合中的元素类型不一致,返回null
Class<?> findCommonElementType(Collection<?> collection)

测试代码

import org.junit.Test;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * org.springframework.util.CollectionUtils用法测试
 *
 * @author lyn
 * @date 2022/8/18 13:23
 */
public class CollectionUtilsTest {
    /**
     * 判断集合是否为null或者空
     * Map,Collection
     */
    @Test
    public void test1() {
        Collection<Long> collection = new HashSet<>();
        System.out.println(CollectionUtils.isEmpty(collection));
    }

    /**
     * 判断 集合 中是否包含某个对象
     */
    @Test
    public void test2() {
        List<Integer> list = Arrays.asList(3, 1, 4, 2);
        //判断 集合 中是否包含某个对象
        System.out.println(CollectionUtils.containsInstance(list, 1));
        //false
        // 以迭代器的方式,判断 集合 中是否包含某个对象
        System.out.println(CollectionUtils.contains(list.iterator(), "abc"));
        List<Integer> list1 = Arrays.asList(1, 4, 2);
        // 判断 集合 是否包含某些对象中的任意一个(两个集合是否有交集)
        boolean b = CollectionUtils.containsAny(list, list1);
        System.out.println(b);
        //true
    }

    @Test
    public void test3() {
        List<Long> list = new ArrayList<>();
        list.add(1L);
        /// 将 数组 中的元素都添加到 集合 中,第一个参数为数组,第二个参数为集合
        CollectionUtils.mergeArrayIntoCollection(new String[]{"abc", "def"}, list);
        System.out.println(list);
        // 将 Properties 中的键值对都添加到 Map 中
        Properties properties = new Properties();
        properties.put("key1", "abc");
        properties.put("key2", "def");
        Map<String, String> map = new HashMap<>();
        // 将 Properties 中的键值对都添加到 Map 中
        CollectionUtils.mergePropertiesIntoMap(properties, map);
        System.out.println(map);
        //{key1=abc, key2=def}

        List<Integer> list1 = Arrays.asList(3, 1, 4, 2);
        List<Integer> list2 = Arrays.asList(1, 4, 2, 3);
        // 返回参数 candidates 中第一个存在于参数 source 中的元素
        Integer firstMatch = CollectionUtils.findFirstMatch(list1, list2);
        System.out.println(firstMatch);
        // 1

        // 返回 List/Set 中元素的类型,如果集合中的元素类型不一致,返回null
        Class<?> commonElementType = CollectionUtils.findCommonElementType(list);
        System.out.println(commonElementType);
        //null
        System.out.println(CollectionUtils.findCommonElementType(list1));
        //class java.lang.Integer
    }

    /**
     * 数组转换成集合,参数必须保证为数组或null,如果不是数组类型,会抛出异常
     */
    @Test
    public void test4() {
        //数组转换成集合
        List<?> list = CollectionUtils.arrayToList(new String[]{"1", "2"});
        List<String> list1 = (List<String>) list;
        System.out.println(list1);
    }

    @Test
    public void test5() {

        List<Object> list = new ArrayList<>();
        list.add(1L);
        list.add(2);
        list.add("5");
        list.add(2);
        //返回 List/Set 中指定类型的元素。指定类型的元素只能有一个,如果是多个的话返回null
        String valueOfType = CollectionUtils.findValueOfType(list, String.class);
        System.out.println(valueOfType);

    }

    @Test
    public void test6() {

        List<Object> list = new ArrayList<>();
        list.add(1L);
        list.add(1L);
        list.add(2);
        //判断 集合中的每个元素是否唯一
        boolean b = CollectionUtils.hasUniqueObject(list);
        System.out.println(b);
        //false
    }
}
posted @ 2022-11-03 11:01  进击的小蔡鸟  阅读(44)  评论(0编辑  收藏  举报