StringUtils在commons-lang3和commons-lang中的区别

最近经常需要对String做一些判断和处理,于是就用到了Apache提供的StringUtils这个工具类,用的时候发现有两个不同的版本,一个版本位于org.apache.commons.lang下面,另一个则位于org.apache.commons.lang3下面。

查了一下资料,lang3是Apache Commons 团队发布的工具包,要求jdk版本在1.5以上,相对于lang来说完全支持java5的特性,废除了一些旧的API。该版本无法兼容旧有版本,于是为了避免冲突改名为lang3。这些东西就不再细说了,我们来看看StringUtils中常用的一些方法有什么改变吧。

PS.本文的java版本为1.8。
1.isEmpty、isNotEmpty、isBlank、isNotBlank

先贴源码

    //lang
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    public static boolean isBlank(String str) {
        int strLen;
        if(str != null && (strLen = str.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if(!Character.isWhitespace(str.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }
    //lang3
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

    public static boolean isBlank(CharSequence cs) {
        int strLen;
        if(cs != null && (strLen = cs.length()) != 0) {
            for(int i = 0; i < strLen; ++i) {
                if(!Character.isWhitespace(cs.charAt(i))) {
                    return false;
                }
            }

            return true;
        } else {
            return true;
        }
    }

    public static boolean isNotBlank(CharSequence cs) {
        return !isBlank(cs);
    }

可以看到这几个方法逻辑毫无变化,只是参数类型变了,由String变为CharSequence。那么这个CharSequence是什么呢?我们看看它的源码:

/**
 * A <tt>CharSequence</tt> is a readable sequence of <code>char</code> values. This
 * interface provides uniform, read-only access to many different kinds of
 * <code>char</code> sequences.
 * A <code>char</code> value represents a character in the <i>Basic
 * Multilingual Plane (BMP)</i> or a surrogate. Refer to <a
 * href="Character.html#unicode">Unicode Character Representation</a> for details.
 *
 * <p> This interface does not refine the general contracts of the {@link
 * java.lang.Object#equals(java.lang.Object) equals} and {@link
 * java.lang.Object#hashCode() hashCode} methods.  The result of comparing two
 * objects that implement <tt>CharSequence</tt> is therefore, in general,
 * undefined.  Each object may be implemented by a different class, and there
 * is no guarantee that each class will be capable of testing its instances
 * for equality with those of the other.  It is therefore inappropriate to use
 * arbitrary <tt>CharSequence</tt> instances as elements in a set or as keys in
 * a map. </p>
 *
 * @author Mike McCloskey
 * @since 1.4
 * @spec JSR-51
 */

public interface CharSequence {

    int length();

    char charAt(int index);

    CharSequence subSequence(int start, int end);

    public String toString();
}

CharSequence是一个字符序列的接口,其中定义了一些常用的如length()、subSequence()等方法,String也实现了这个接口。当然大家可能在String里用到的都是subString(),实际上String也实现了subSequence()这个方法,只是直接指向了subString()。

//String中的subSequence方法
public CharSequence subSequence(int beginIndex, int endIndex) {
        return this.substring(beginIndex, endIndex);
}

lang3中使用CharSequence最大的好处就是令这些方法用处更加广泛,不止局限于String,其他一些实现了该接口的类也可以使用StringUtils中的这些方法去进行一些操作。另外我发现很多nio中的类都实现了这个接口,个人猜测可能也有为nio服务的目的。

2.equals
//lang
public static boolean equals(String str1, String str2) {
    return str1 == null?str2 == null:str1.equals(str2);
}
//lang3
public static boolean equals(CharSequence cs1, CharSequence cs2) {
        return cs1 == cs2?true:(cs1 != null && cs2 != null?(cs1.length() != cs2.length()?false:(cs1 instanceof String && cs2 instanceof String?cs1.equals(cs2):CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length()))):false);
}

在lang中,第一步是先判断str1是否为空,而在lang3中,第一步则是先判断两个对象是否相同。这个不难理解,如果两个对象的地址相同,那么它们指向的就是同一个对象,内容肯定相同。

3.isAnyEmpty、isNoneEmpty、isAllEmpty
    //lang3
    public static boolean isAnyEmpty(CharSequence... css) {
        if(ArrayUtils.isEmpty(css)) {
            return false;
        } else {
            CharSequence[] var1 = css;
            int var2 = css.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                CharSequence cs = var1[var3];
                if(isEmpty(cs)) {
                    return true;
                }
            }

            return false;
        }
    }

    public static boolean isNoneEmpty(CharSequence... css) {
        return !isAnyEmpty(css);
    }

    public static boolean isAllEmpty(CharSequence... css) {
        if(ArrayUtils.isEmpty(css)) {
            return true;
        } else {
            CharSequence[] var1 = css;
            int var2 = css.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                CharSequence cs = var1[var3];
                if(isNotEmpty(cs)) {
                    return false;
                }
            }

            return true;
        }
    }

在lang3中,还加入了一些同时判断多个参数的方法,可以看到实际上是将参数列表放入一个CharSequence数组中,然后遍历调用之前的isEmpty等方法。判断blank也有类似的方法。

可能有人会觉得,很多方法String本身就有啊,为什么还要用StringUtils提供的呢?抛开参数类型不谈,我们可以看到,StringUtils中的方法大多都做了空校验,如果为空时会返回Null或者空串,而String本身的方法在很多传入参数或对象本身为空的时候都会报空指针错误。

常用方法就先介绍到这里,以后有机会再继续更。

PS.看CharSequence源码的时候发现里面居然有实现了的方法,只是返回值前面加了个default。查了一下发现是Java8的新特性,可以在接口里面定义default方法,从而使得接口在进行扩展的时候,不会破坏与接口相关的实现类代码。可以参考Java 8新特性——default方法(defender方法)介绍

  • 17
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
commons-lang3.3.1.jar、Apache Commons的一个,包含了一些数据类型工具类,是java.lang.*的扩展。必须使用的jar包。为JRE5.0+的更好的版本所提供 Jar文件包含的类: META-INF/MANIFEST.MFMETA-INF/LICENSE.txtMETA-INF/NOTICE.txtorg.apache.commons.lang.ArrayUtils.class org.apache.commons.lang.BitField.class org.apache.commons.lang.BooleanUtils.class org.apache.commons.lang.CharEncoding.class org.apache.commons.lang.CharRange.class org.apache.commons.lang.CharSet.class org.apache.commons.lang.CharSetUtils.class org.apache.commons.lang.CharUtils.class org.apache.commons.lang.ClassUtils.class org.apache.commons.lang.Entities$ArrayEntityMap.class org.apache.commons.lang.Entities$BinaryEntityMap.class org.apache.commons.lang.Entities$EntityMap.class org.apache.commons.lang.Entities$HashEntityMap.class org.apache.commons.lang.Entities$LookupEntityMap.class org.apache.commons.lang.Entities$MapIntMap.class org.apache.commons.lang.Entities$PrimitiveEntityMap.class org.apache.commons.lang.Entities$TreeEntityMap.class org.apache.commons.lang.Entities.class org.apache.commons.lang.IllegalClassException.class org.apache.commons.lang.IncompleteArgumentException.class org.apache.commons.lang.IntHashMap$Entry.class org.apache.commons.lang.IntHashMap.class org.apache.commons.lang.LocaleUtils.class org.apache.commons.lang.NotImplementedException.class org.apache.commons.lang.NullArgumentException.class org.apache.commons.lang.NumberRange.class org.apache.commons.lang.NumberUtils.class org.apache.commons.lang.ObjectUtils$Null.class org.apache.commons.lang.ObjectUtils.class org.apache.commons.lang.RandomStringUtils.class org.apache.commons.lang.SerializationException.class org.apache.commons.lang.SerializationUtils.class org.apache.commons.lang.StringEscapeUtils.class org.apache.commons.lang.StringUtils.class org.apache.commons.lang.SystemUtils.class org.apache.commons.lang.UnhandledException.class org.apache.commons.lang.Validate.class org.apache.commons.lang.WordUtils.class org.apache.commons.lang.builder.CompareToBuilder.class org.apache.commons.lang.builder.EqualsBuilder.class org.apache.commons.lang.builder.HashCodeBuilder.class org.apache.commons.lang.builder.ReflectionToStringBuilder$1.class org.apache.commons.lang.builder.ReflectionToStringBuilder.class org.apache.commons.lang.builder.StandardToStringStyle.class org.apache.commons.lang.builder.ToStringBuilder.class org.apache.commons.lang.builder.ToStringStyle$DefaultToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$NoFieldNameToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$ShortPrefixToStringStyle.class org.apache.commons.lang.builder.ToStringStyle$SimpleToStringStyle.class org.apache.commons.lang.builder.ToStringStyle.class org.apache.commons.lang.enum.Enum$Entry.class org.apache.commons.lang.enum.Enum.class org.apache.commons.lang.enum.EnumUtils.class org.apache.commons.lang.enum.ValuedEnum.class org.apache.commons.lang.enums.Enum$Entry.class org.apache.commons.lang.enums.Enum.class org.apache.commons.lang.enums.EnumUtils.class org.apache.commons.lang.enums.ValuedEnum.class org.apache.commons.lang.exception.ExceptionUtils.class org.apache.commons.lang.exception.Nestable.class org.apache.commons.lang.exception.NestableDelegate.class org.apache.commons.lang.exception.NestableError.class org.apache.commons.lang.exception.NestableException.class org.apache.commons.lang.exception.NestableRuntimeException.class org.apache.commons.lang.math.DoubleRange.class org.apache.commons.lang.math.FloatRange.class org.apache.commons.lang.math.Fraction.class org.apache.commons.lang.math.IntRange.class org.apache.commons.lang.math.JVMRandom.class org.apache.commons.lang.math.LongRange.class org.apache.commons.lang.math.NumberRange.class org.apache.commons.lang.math.NumberUtils.class org.apache.commons.lang.math.RandomUtils.class org.apache.commons.lang.math.Range.class org.apache.commons.lang.mutable.Mutable.class org.apache.commons.lang.mutable.MutableBoolean.class org.apache.commons.lang.mutable.MutableByte.class org.apache.commons.lang.mutable.MutableDouble.class org.apache.commons.lang.mutable.MutableFloat.class org.apache.commons.lang.mutable.MutableInt.class org.apache.commons.lang.mutable.MutableLong.class org.apache.commons.lang.mutable.MutableObject.class org.apache.commons.lang.mutable.MutableShort.class org.apache.commons.lang.text.CompositeFormat.class org.apache.commons.lang.text.StrBuilder$StrBuilderReader.class org.apache.commons.lang.text.StrBuilder$StrBuilderTokenizer.class org.apache.commons.lang.text.StrBuilder$StrBuilderWriter.class org.apache.commons.lang.text.StrBuilder.class org.apache.commons.lang.text.StrLookup$MapStrLookup.class org.apache.commons.lang.text.StrLookup.class org.apache.commons.lang.text.StrMatcher$CharMatcher.class org.apache.commons.lang.text.StrMatcher$CharSetMatcher.class org.apache.commons.lang.text.StrMatcher$NoMatcher.class org.apache.commons.lang.text.StrMatcher$StringMatcher.class org.apache.commons.lang.text.StrMatcher$TrimMatcher.class org.apache.commons.lang.text.StrMatcher.class org.apache.commons.lang.text.StrSubstitutor.class org.apache.commons.lang.text.StrTokenizer.class org.apache.commons.lang.time.DateFormatUtils.class org.apache.commons.lang.time.DateUtils$DateIterator.class org.apache.commons.lang.time.DateUtils.class org.apache.commons.lang.time.DurationFormatUtils$Token.class org.apache.commons.lang.time.DurationFormatUtils.class org.apache.commons.lang.time.FastDateFormat$CharacterLiteral.class org.apache.commons.lang.time.FastDateFormat$NumberRule.class org.apache.commons.lang.time.FastDateFormat$PaddedNumberField.class org.apache.commons.lang.time.FastDateFormat$Pair.class org.apache.commons.lang.time.FastDateFormat$Rule.class org.apache.commons.lang.time.FastDateFormat$StringLiteral.class org.apache.commons.lang.time.FastDateFormat$TextField.class org.apache.commons.lang.time.FastDateFormat$TimeZoneDisplayKey.class org.apache.commons.lang.time.FastDateFormat$TimeZoneNameRule.class org.apache.commons.lang.time.FastDateFormat$TimeZoneNumberRule.class org.apache.commons.lang.time.FastDateFormat$TwelveHourField.class org.apache.commons.lang.time.FastDateFormat$TwentyFourHourField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitMonthField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitNumberField.class org.apache.commons.lang.time.FastDateFormat$TwoDigitYearField.class org.apache.commons.lang.time.FastDateFormat$UnpaddedMonthField.class org.apache.commons.lang.time.FastDateFormat$UnpaddedNumberField.class org.apache.commons.lang.time.FastDateFormat.class org.apache.commons.lang.time.StopWatch.class
### 回答1: org.apache.commons commons-lang3-3.1是一个Apache软件基金会的一个实用程序库。它包含了大量的实用工具类和方法,使Java开发人员可以更快、更方便地编写Java代码。在这个库,开发人员可以找到很多常用的功能,例如字符串操作、日期和时间处理、随机数生成、数组操作、文件操作、数学计算等等。通过这个库,我们可以快速地实现各种功能,提高我们的开发效率。 下载org.apache.commons commons-lang3-3.1非常简单。可以在Apache官网上进行下载,也可以在Maven央仓库下载。只需要将对应的jar包加入到我们的工程即可使用。通过使用Org.apache.commons commons-lang3-3.1这个工具集,我们可以在Java开发更加得心应手,更加高效地完成开发任务,为我们的项目赢得更多的成功。 ### 回答2: org.apache.commons commons-lang3-3.1是一个Apache软件基金会提供的开源Java类库,主要提供了一系列通用的工具类和方法,用于字符串处理、日期处理、基本类型转换等常用操作,简化了Java开发过程的一些常见任务。 下载这个类库可以到Apache官网的下载页面进行下载,并且也可在Maven仓库通过依赖的方式引入。使用时只需要将其添加到Java项目的classpath即可。 这个版本的commons-lang3包含了很多实用的工具类和方法,比如StringUtils类可以方便地处理字符串的格式化、剪切、替换、分割等操作;DateUtils类提供了对日期和时间的各种处理,包括格式化、加减、比较等等;ArrayUtils类提供了对数组的各种操作,包括复制、添加、查找等等。这些工具类的使用可以大大简化Java开发的工作量,提高代码的可读性和可维护性。 总的来说,org.apache.commons commons-lang3-3.1是一个非常实用的Java类库,推荐给Java开发者使用。 ### 回答3: org.apache.commons commons-lang3-3.1是一个基于Java语言编写的开源软件库。它包含了一系列通用的工具类、方法和实用函数,可以帮助开发者更加高效地完成各种Java应用程序的开发工作。 这个开源软件库主要包含了字符串处理、文件处理、日期时间处理、随机数生成、对象操作、反射等多个方面的功能模块。在实际开发,我们可以直接引入这个软件库,并调用其封装好的方法和函数,来完成一些常规性的编码任务。 org.apache.commons commons-lang3-3.1的下载方式是在Apache官网上进行下载。我们可以在官网上找到相应的下载链接,并选择适用于当前开发环境的版本进行下载。下载后,我们需要将其集成到当前的Java应用程序,并在代码引入相关的依赖库和包,才能顺利使用其的功能模块。 总之,org.apache.commons commons-lang3-3.1是一个常用的Java开源软件库,封装了多种常用的工具类、方法和实用函数,可以大大简化Java程序的开发过程。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值