Guava库中的Preconditions类提供了一些静态方法,用于在程序中执行参数的检查和验证。这些方法在编写健壮和可维护的代码时非常有用
-
checkArgument(boolean expression):
- 作用:用于验证方法的参数是否满足某个条件。如果条件不满足,则抛出
IllegalArgumentException。 - 示例:
int age = -1; Preconditions.checkArgument(age > 0, "Age must be positive"); - 说明:如果
age不大于0,就会抛出IllegalArgumentException,并显示消息“Age must be positive”。
- 作用:用于验证方法的参数是否满足某个条件。如果条件不满足,则抛出
-
checkNotNull(T reference):
- 作用:用于验证方法的参数是否为
null。如果参数为null,则抛出NullPointerException。 - 示例:
String name = null; Preconditions.checkNotNull(name, "Name cannot be null"); - 说明:如果
name为null,就会抛出NullPointerException,并显示消息“Name cannot be null”。
- 作用:用于验证方法的参数是否为
-
checkState(boolean expression):
- 作用:用于验证对象的状态是否满足某个条件。如果条件不满足,则抛出
IllegalStateException。 - 示例:
boolean isStarted = false; Preconditions.checkState(isStarted, "The service has not been started yet"); - 说明:如果
isStarted为false,就会抛出IllegalStateException,并显示消息“The service has not been started yet”。
- 作用:用于验证对象的状态是否满足某个条件。如果条件不满足,则抛出
-
checkElementIndex(int index, int size):
- 作用:用于验证集合的索引是否有效。如果索引无效,则抛出
IndexOutOfBoundsException。 - 示例:
int index = 5; int size = 3; Preconditions.checkElementIndex(index, size, "Index out of bounds"); - 说明:如果
index不在有效范围内(0到size-1),就会抛出IndexOutOfBoundsException,并显示消息“Index out of bounds”。
- 作用:用于验证集合的索引是否有效。如果索引无效,则抛出
-
checkPositionIndex(int index, int size):
- 作用:用于验证集合的插入位置是否有效。如果位置无效,则抛出
IndexOutOfBoundsException。 - 示例:
int position = 4; int size = 3; Preconditions.checkPositionIndex(position, size, "Position out of bounds"); - 说明:如果
position不在有效范围内(0到size),就会抛出IndexOutOfBoundsException,并显示消息“Position out of bounds”。
- 作用:用于验证集合的插入位置是否有效。如果位置无效,则抛出
-
checkPositionIndexes(int start, int end, int size):
- 作用:用于验证集合的子区间(子列表)是否有效。如果区间无效,则抛出
IndexOutOfBoundsException。 - 示例:
int start = 2; int end = 5; int size = 4; Preconditions.checkPositionIndexes(start, end, size, "Invalid sublist range"); - 说明:如果
start和end不在有效范围内(0到size),或者start大于end,就会抛出IndexOutOfBoundsException,并显示消息“Invalid sublist range”。
- 作用:用于验证集合的子区间(子列表)是否有效。如果区间无效,则抛出
这些Preconditions方法在代码中提供了一种简洁而一致的方式来进行参数和状态检查,从而有助于编写更加健壮的代码。