StringUtils apache工具类小记

来源:互联网 发布:linux设置默认启动项 编辑:程序博客网 时间:2024/05/19 06:49

今天接触了StringUtils,这个apache的工具类,源码里有不少的方法用来方便大家 。最重要的是isEmpty和isBlank方法。下面的代码注解里写得很清楚了。
isEmpty()方法中, 判断逻辑就是这一句: return str == null || str.length() == 0;
当传入的参数str等于null ,或者它的长度为零时,那么isEmpty方法的返回值就是true,也就是说当传入的参数为空字符串或者null时,返回值为true。注释中提供了好几个例子,可以帮助大家理解。注意,whitespace在这个方法中返回false,意为notEmpty.

   // Empty checks    //-----------------------------------------------------------------------    /**     * <p>Checks if a String is empty ("") or null.</p>     *     * <pre>     * StringUtils.isEmpty(null)      = true     * StringUtils.isEmpty("")        = true     * StringUtils.isEmpty(" ")       = false     * StringUtils.isEmpty("bob")     = false     * StringUtils.isEmpty("  bob  ") = false     * </pre>     *     * <p>NOTE: This method changed in Lang version 2.0.     * It no longer trims the String.     * That functionality is available in isBlank().</p>     *     * @param str  the String to check, may be null     * @return <code>true</code> if the String is empty or null     */    public static boolean isEmpty(String str) {        return str == null || str.length() == 0;    } 

isBlank方法测试的是是否是whitespace或者为 空字符串或者null.

 /**     * <p>Checks if a String is whitespace, empty ("") or null.</p>     *     * <pre>     * StringUtils.isBlank(null)      = true     * StringUtils.isBlank("")        = true     * StringUtils.isBlank(" ")       = true     * StringUtils.isBlank("bob")     = false     * StringUtils.isBlank("  bob  ") = false     * </pre>     *     * @param str  the String to check, may be null     * @return <code>true</code> if the String is null, empty or whitespace     * @since 2.0     */    public static boolean isBlank(String str) {        int strLen;        if (str == null || (strLen = str.length()) == 0) {            return true;        }        for (int i = 0; i < strLen; i++) {            if ((Character.isWhitespace(str.charAt(i)) == false)) {                return false;            }        }        return true;    }
0 0
原创粉丝点击