通过该类,可完成一些基本校验,其提供的静态方法如下:
方法 | 备注 |
checkArgument | 如果校验的表达式为false,则抛出 IllegalArgumentException 异常 |
checkNotNull | 判断是否为空,若为空,则抛出NullPointerException |
checkElementIndex | 判断索引及长度是否合法,index >= 0 且 index < size,如果不满足条件抛出异常 IndexOutOfBoundsException |
checkPositionIndex | 与 checkElementIndex 类似,区别是 index <= size ,如果不满足条件抛出异常 IndexOutOfBoundsException |
checkPositionIndexes | 与 checkPositionIndex 类似,start >= 0 && end >= start && end <= size, 如果不满足抛出异常 IndexOutOfBoundsException |
checkState | 用法与checkArgument基本一样,也是根据布尔表达式判断,区别是如果表达式结果为false,抛出 IllegalStateException 异常 |
public void test(){
try {
//Preconditions.checkArgument(0>1);
Preconditions.checkArgument(0>1 ,"入参错误");
Preconditions.checkArgument(0>1,"入参值:%s,有误", 1);
} catch (IllegalArgumentException e){
System.err.println(e.getMessage());
}
try {
Object obj = null;
//Preconditions.checkNotNull(obj);
Preconditions.checkNotNull(obj,"obj不能为空");
Preconditions.checkNotNull(obj,"obj不能为%s", "null" );
} catch (NullPointerException e) {
System.err.println(e.getMessage());
}
try {
Preconditions.checkElementIndex(0,0, "test");
} catch (IndexOutOfBoundsException e) {
System.err.println(e.getMessage());
}
try {
Preconditions.checkPositionIndex(1,0, "test");
} catch (IndexOutOfBoundsException e){
System.err.println(e.getMessage());
}
try {
Preconditions.checkPositionIndexes(3, 2, 3);
} catch (IndexOutOfBoundsException e) {
System.err.println(e.getMessage());
}
try {
Preconditions.checkState(0 > 1, "%s+%s", "错误", "1");
} catch (IllegalStateException e) {
System.err.println(e.getMessage());
}
}
输出:
入参错误
obj不能为空
test (0) must be less than size (0)
test (1) must not be greater than size (0)
end index (2) must not be less than start index (3)
错误+1