概述
Guava provides a number of precondition checking utilities. We strongly recommend importing these statically.
Each method has three variants:
- No extra arguments. Any exceptions are thrown without error messages.
- An extra Object argument. Any exception is thrown with the error message object.toString().
- An extra String argument, with an arbitrary number of additional Object arguments. This behaves something like printf, but for GWT compatibility and efficiency, it only allows %s indicators.
Note: checkNotNull, checkArgument and checkState have a large number of overloads taking combinations of primitive and Object parameters rather than a varargs array — this allows calls such as those above to avoid both primitive boxing and varags array allocation in the vast majority of cases.
使用建議
We recommend that you split up preconditions into distinct lines, which can help you figure out which precondition failed while debugging. Additionally, you should provide helpful error messages, which is easier when each check is on its own line.
We preferred rolling our own preconditions checks over e.g. the comparable utilities from Apache Commons for a few reasons. Briefly:
- After static imports, the Guava methods are clear and unambiguous.
checkNotNull
makes it clear what is being done, and what exception will be thrown. -
checkNotNull
returns its argument after validation, allowing simple one-liners in constructors:this.field = checkNotNull(field);
. - Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use
checkNotNull
overObjects.requireNonNull
)
實(shí)例
public static void testPreconditions(){
// ====都是快速失敗顶猜,直接拋出異常
Integer i1 = 2;
// 檢查參數(shù)
Preconditions.checkArgument(i1>1);
Preconditions.checkArgument(i1>1, "ok");
String s1 = "s1";
// 是否空
s1 = Preconditions.checkNotNull(s1, "%s is null", s1);
// Ensures the truth of an expression involving the state of the calling instance
Preconditions.checkState(s1 != null);
List<Integer> list1 = Arrays.asList(1, 2, 3,4);
// 檢查元素index是否越界
Preconditions.checkElementIndex(2, list1.size());
// 檢查position是否越界
Preconditions.checkPositionIndex(1, list1.size());
// 檢查[start, end]是否越界
Preconditions.checkPositionIndexes(1, 3, list1.size());
}
Ref:
https://github.com/google/guava/wiki/PreconditionsExplained