妖刀StringUtils
7月入りました~2014年も後半戦突入だ~
後半戦は縦パス縦パスな日々を送りたいものだ。
今日は開発を通して、便利~!
と思ったものについてまとめたいと思うよ。
ひとつめ、Apache Commons Langの StringUtils!
・StringUtilsとは
・String オブジェクトのメソッドを拡張したユーティリティクラス。
…という言い方だとStringを継承しているように感じる!と
先輩からご指摘があったので、言い直し!
StringUtilsはStringを扱う便利なメソッドが集まったユーティリティクラス!
by大阪の某big_west先輩
・String オブジェクトのメソッドとの違いは、
NullPointerException が発生しないように null判定がされていること。
・ダウンロードURL
http://commons.apache.org/proper/commons-lang/download_lang.cgi
中でもあたしが「お~!」と思ったAPIはこの4つ!
(サンプルコードはAPIから拝借しますた。)
・isEmpty()
Checks if a String is empty ("") or null.
文字列が空文字または nullの時にtrueを返す。
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
・isNotEmpty()
Checks if a String is not empty ("") and not null.
文字列が空文字または nullではない時にtrueを返す。
StringUtils.isEmpty(null) = false
StringUtils.isEmpty("") = false
StringUtils.isEmpty(" ") = true
StringUtils.isEmpty("bob") = true
StringUtils.isEmpty(" bob ") = true
・isBlank()
Checks if a String is whitespace, empty ("") or null.
空白文字も空文字とみなし、
文字列が空文字または nullの時、かつ空白文字の時にtrueを返す。
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = true
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
・isNotBlank()
Checks if a String is not empty (""), not null and not whitespace only.
空白文字も空文字とみなし、
文字列が空文字または nullではない時、かつ空白文字でない時にtrueを返す。
StringUtils.isEmpty(null) = false
StringUtils.isEmpty("") = false
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = true
StringUtils.isEmpty(" bob ") = true
空白を許可したい場合以外は、
isBlankを使うことがセオリーらしいです。
今まで
String str = "shiorin";
if(str != null && "".equals(str)){
return false;
}
とか地道に記述していたところを、
String str = "shiorin";
StringUtils.isNotEmpty(str);
と記述するだけでいいなんて!すごい!画期的!
もっと早くに知りたかった!
この他にもStringUtilsクラスには
文字列に関するロジックが沢山あったよ。
文字列がアルファベットまたは数字ならtrueを返す isAlphanumeric()とか、
null を考慮して文字列を比較する equals()とか…
String オブジェクトのメソッドとの違いは…でも書いたけど
やっぱりStringUtilsの一番の利点は
文字列とnullを比較してもぬるぽ(ガッ)で落ちないところですな!
ほんと、もっと早くに知りたかった(笑)
今日はStringUtilsの他に、Jacksonについてもまとめようと思ってたんだけど
ねむいのでまた明日。
今日は先輩に念願のサワークリームオニオンをおすそ分けしてもらったり、
カツが起きてる間に家に帰れたりで、ちょっと嬉しかったな~
でも相変わらずはてな記法の使い方分からずでアレだな~
明日も頑張ろ。テストからだ~