google guavaに含まれるPreconditionsクラスの説明。
このクラスはJavaに含まれるExceptionを省略したもの。このクラスの目的はコードの可読性を高めること。簡単に言うと文章を短くして見やすくしようとのこと。
checkNotNullメソッド
NullPointerExceptionを省略したもの
CheckNotNullSample.java
import com.google.common.base.Preconditions;
public class CheckNotNullSample {
public static void main(String[] args) {
String string = null;
//if(string == null){
//throw new NullPointerException();
//}
Preconditions.checkNotNull(string);
}
}
実行結果は
Exception in thread "main" java.lang.NullPointerException
at CheckNotNullSample.main(CheckNotNullTest.java:26)
となり、NullPointerExceptionを投げてくれる。
checkArgumentメソッド
IllegalArgumentExceptionを省略したもの
CheckArgumentSample.java
import com.google.common.base.Preconditions;
public class CheckArgumentSample {
public static void main(String[] args) {
String[] string = {};
//if(string == null){
//throw new IllegalArgumentException();
//}
Preconditions.checkArgument(string.length > 0);
}
}
実行結果は
Exception in thread "main" java.lang.IllegalArgumentException
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
at CheckArgumentSample.main(CheckArgumentTest.java:13)
となり、IllegalArgumentExceptionを投げる。