PreConditions(先决条件)
checkArgument(boolean expression, [String errorMsgTemplate], [String errorMsgArgs]):expression如果为false,则抛出IllegalArgumentException异常,并输出错误消息
Preconditions.checkArgument(1 > 2); // throw IllegalArgumentException Preconditions.checkArgument(1 > 2, "1 lower than 2"); // throw IllegalArgumentException: 1 lower than 2 Preconditions.checkArgument(1 > 2, "%s lower than %s", 1, 2); // throw IllegalArgumentException: 1 lower than 2
T checkNotNul (T ref):如果ref为null,则抛出NullPointerException;否则返回ref的引用(该方法的其他几种重载可以自定义输出错误消息)
String s1 = Preconditions.checkNotNull("1"); s1; // 1 String s2 = Preconditions.checkNotNull(null);// throw NullPointerException
void checkState (boolean expression):用法与checkArgument相同,只不过抛出的是IllegalStateException异常
int checkElementIndex (int index, int size):检查索引是否在[0, size)之间,不在则抛出IndexOutOfBoundsException异常
Preconditions.checkElementIndex(3, 3); // throw IndexOutOfBoundsException: index (3) must be less than size (3)
int checkPositionIndex (int index, int size):检查索引是否在[0, size]之间,不在则抛出IndexOutOfBoundsException异常
void checkPositionIndexes (int start, int end, int size):检查[start, end)是否在[0, size]之间,不在则抛出IndexOutOfBoundsException异常
使用优点:
- 语义明确
- 抛出的异常明确
- 可以自定义错误消息的格式
- 由于方法在校验后返回了参数本身,所以可以在写在一行里,简化代码