why?
- 在编写程序的时候,很多时候都需要检查输入的参数是否符合我们的需要,比如人的年龄要大于0,小于100,值不能为NUll如果不符合这两个要求,我们将认为这个对象是不合法的.
- 检测是非常有必要的,不检查那个不得了了啊
- 很多情况下,不满足就进行处理,那个意外伤害性很大。
参考文档
- https://github.com/google/guava/wiki/PreconditionsExplained
- https://willnewii.gitbooks.io/google-guava/content/chapter1/%E5%89%8D%E7%BD%AE%E6%9D%A1%E4%BB%B6.html
简单说明
Guava在Preconditions类中提供了若干前置条件判断的实用方法,每个方法都有三个变种
* 没有额外参数:抛出的异常中没有错误消息;
* 有一个Object对象作为额外参数:抛出的异常使用Object.toString() 作为错误消息;
* 有一个String对象作为额外参数,并且有一组任意数量的附加Object对象:这个变种处理异常消息的方式有点类似printf,但考虑GWT的兼容性和效率,只支持%s指示符。
比如
checkArgument(i >= 0, "Argument was %s but expected nonnegative", i);
checkArgument(i < j, "Expected i < j, but %s > %s", i, j);
源码
- Preconditions.checkArgument
一个参数
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
两个参数
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
三个参数,打印而已
public static void checkArgument(
boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
上面看出来,每一个方法都有很多的重载
使用
- checkArgument(boolean)
检查boolean是否为true,用来检查传递给方法的参数。失败IllegalArgumentException
public static void test1(){
int age = 20000;
Preconditions.checkArgument(age>0 && age<100,"age is error %s",age);
}
Exception in thread "main" java.lang.IllegalArgumentException: age is error 20000
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:168)
.......
checkNotNull(T)
检查value是否为null,该方法直接返回value,因此可以内嵌使用checkNotNull。失败NullPointerExceptioncheckState(boolean)
感觉这个和第一个差不多啊
用来检查对象的某些状态。失败IllegalStateException
public static void test2(){
int age = 20000;
Preconditions.checkState(age>0 && age<100,"age is error %s",age);
}
Exception in thread "main" java.lang.IllegalStateException: age is error 20000
at com.google.common.base.Preconditions.checkState(Preconditions.java:493)
at Guava.GooglePreCondition.test2(GooglePreCondition.java:16)
.......
checkElementIndex(int index, int size)
检查index作为索引值对某个列表、字符串或数组是否有效。index>=0 && index< size
失败IndexOutOfBoundsException,数组越界的时候需要这个checkPositionIndex(int index, int size)
检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 && index<=size。
失败 IndexOutOfBoundsExceptioncheckPositionIndexes(int start, int end, int size)、
检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效,失败IndexOutOfBoundsException
意义
索引值常用来查找列表、字符串或数组中的元素,如List.get(int), String.charAt(int)
位置值和位置范围常用来截取列表、字符串或数组,如List.subList(int,int), String.substring(int)