LoginSignup
6
7

More than 5 years have passed since last update.

Google Guavaまとめ1(Preconditions)

Last updated at Posted at 2016-10-22

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を投げる。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7