Preconditions比较简单的
前置条件:让方法调用的前置条件判断更简单。
准备工作
官方仓库:https://github.com/google/guava
在线wiki:
https://github.com/google/guava/wiki/PreconditionsExplained
com.google.common.base.Preconditions
方法声明 | 描述 | 失败时抛出的异常 |
---|---|---|
checkArgument(boolean) |
检查boolean是否为true,传入false抛出异常 | IllegalArgumentException |
checkNotNull(T) |
检查<T> value为null直接抛出异常,否则直接返回value。 | NullPointerException |
checkState(boolean) |
用来检查对象的某些状态。 | IllegalStateException |
checkElementIndex(int index, int size) |
检查index作为索引值对某个列表、字符串或数组是否有效。index>=0 && index<size
|
IndexOutOfBoundsException |
checkPositionIndex(int index, int size) |
检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 && index<=size
|
IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) |
检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效 | IndexOutOfBoundsException |
Preconditions.checkArgument(false);Preconditions.checkArgument(false,"this is a test!"); //this is a test!
Preconditions.checkArgument(false,"%s is a %s","hjh","pig"); //hjh is a pig
Preconditions.checkElementIndex(20, 10); //java.lang.IndexOutOfBoundsException: index (20) must be less than size (10)
Preconditions.checkPositionIndex(20, 10, "desc !!!!"); //java.lang.IndexOutOfBoundsException: desc !!!! (20) must not be greater than size (10)
Preconditions.checkPositionIndex(20, 10); //java.lang.IndexOutOfBoundsException: index (20) must not be greater than size (10)
Preconditions.checkState(false); // java.lang.IllegalStateException
Preconditions.checkNotNull(1);//1
Preconditions.checkNotNull(null,"is null"); //java.lang.NullPointerException: is null
Preconditions.checkNotNull(null, "%s is null !", "object"); //java.lang.NullPointerException: object is null !