Apache Commons Lang使用
在Commons Lang对应的包,并查看相应的文档。
StringUtils
StringUtils位于org.apache.commons.lang包下
参考Apache Commons Lang StringUtils介绍一些常用的方法。
1.public static boolean equals(CharSequence str1, CharSequence str2)方法
文档介绍如下:
比较两个CharSequences,如果表示相同返回true。
处理null会没有异常。两个null会被认为是相同的,比较是大小写敏感的。
StringUtils.equals(null, null) = true
StringUtils.equals(null, "abc") = false
StringUtils.equals("abc", null) = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false
为什么要使用这个方法呢?如下的代码:
public void doStuffWithString(String stringParam) {
if(stringParam.equals("MyStringValue")) {
// do stuff
}
}
这里可能会抛出一个NullPointerException异常
一般的做法是:
public void safeDoStuffWithString1(String stringParam) {
if(stringParam != null && stringParam.equals("MyStringValue")) {
// do stuff
}
}
public void safeDoStuffWithString2(String stringParm) {
if("MyStringValue".equals(stringParam)) {
// do stuff
}
}
但使用StringUtils.equals,使用起来会简单,而且是null安全的。
2.isEmpty, isNotEmpty, isBlank, isNotBlank
通常的做法是,使用java.lang.String.isEmpty(),并检查是否是null
if(myString != null && !myString.isEmpty()) { // urghh
// Do stuff with myString
}
使用StringUtils
if(StringUtils.isNotEmpty(myString)) { // much nicer
// Do stuff with myString
}
Blank与Empty的区别
String someWhiteSpace = " \t \n";
StringUtils.isEmpty(someWhiteSpace); // false
StringUtils.isBlank(someWhiteSpace); // true
isEmpty检查的是否为""或者null
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
isBlank检查的是否为whitespace, empty (“”) 或者 null
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
3.public static String[] split(String str, String separatorChars)方法
如下的例子:
public void possiblyNotWhatYouWant() {
String contrivedExampleString = "one.two.three.four";
String[] result = contrivedExampleString.split(".");
System.out.println(result.length); // 0
}
result.length的结果为0,但只有加上一对斜杠,就可以得到正确的结果。
但是使用StringUtils的方法就不会出现这种情况。
4.public static String join(Iterable iterable, String separator)方法
String[] numbers = {"one", "two", "three"};
StringUtils.join(numbers,","); // returns "one,two,three"
本文介绍了Apache Commons Lang中的StringUtils,讲解了其包括字符串比较、空判断、URL处理等常用方法,强调了这些方法的null安全性和简化代码的优势。

2441

被折叠的 条评论
为什么被折叠?



