Guava 前置条件 Preconditions 类
Preconditions 提供静态方法来检查方法或构造函数,被调用是否给定适当的参数。它检查的先决条件。其方法失败抛出 IllegalArgumentException。
可以简单理解为 guava 提供的 assert 断言。
一、类声明
以下是 com.google.common.base.Preconditions 类的声明:
@GwtCompatible public final class Preconditions
二、类方法
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);
| 方法声明(不包括额外参数) | 描述 | 检查失败时抛出的异常 |
|---|---|---|
checkArgument(boolean) | 检查boolean是否为true,用来检查传递给方法的参数。 | IllegalArgumentException |
checkNotNull(T) | 检查value是否为null,该方法直接返回value,因此可以内嵌使用checkNotNull。 | 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 示例
Java 中的 java.util.Objects 也提供了断言处理,判断非空等验证。
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
/**
* Precondition 断言
* java.util.Objects 断言
* assert 断言
*/
public class PreconditionTest {
/**
* 空异常
*/
@Test
public void test1() {
Object obj = Preconditions.checkNotNull(null);
}
/**
* 空异常提示语
*/
@Test
public void test2() {
Object obj = Preconditions.checkNotNull(null, "对象不能为空");
}
/**
* 空异常,带格式化的提示语
*/
@Test
public void test3() {
Object obj = Preconditions.checkNotNull(null, "对象不能为空,并且长度必须为 %s", 6);
}
/**
* IllegalArgumentException 异常
*/
@Test
public void test4() {
Preconditions.checkArgument(false);
}
/**
* IllegalArgumentException 异常 - 带提示语
*/
@Test
public void test5() {
Preconditions.checkArgument(false, "未通过验证");
}
/**
* IllegalStateException 异常
*/
@Test
public void test6() {
Preconditions.checkState(false, "未通过验证");
}
/**
* IllegalStateException 异常 - 带提示语
*/
@Test
public void test7() {
Preconditions.checkState(false, "未通过验证");
}
/**
* IndexOutOfBoundsException 异常
*/
@Test
public void test8() {
List<String> list = Arrays.asList("A", "B", "C");
Preconditions.checkElementIndex(10, list.size());
}
/**
* IndexOutOfBoundsException 异常 - 带提示语
*/
@Test
public void test9() {
List<String> list = ImmutableList.of();
Preconditions.checkElementIndex(10, list.size(), "元素长度不正确");
}
/**
* java.util.Objects 断言
*/
@Test
public void test10() {
Object obj = Objects.requireNonNull(null, "对象不能为空");
}
/**
* assert 断言
*/
@Test
public void test11() {
List<String> list = null;
assert list != null : "list 不能为空";
}
}四、相关文章
未经允许请勿转载:程序喵 » Google Guava 快速入门 —— 【基础】前置条件 Preconditions 类
程序喵