Guava provides a number of precondition checking utilities. We strongly recommend importing these statically. (How to do this easily in Eclipse.)
Guava提供了一系列precondition检查工具. 我们强烈推荐你静态引入这些工具
Each method has three variants:
每种方法都有三种变体
checkArgument(i >=0,"Argument was %s but expected nonnegative", i);
checkArgument(i < j,"Expected i < j, but %s > %s", i, j);
Signature (not including extra args) | Description | Exception thrown on failure |
checkArgument(boolean) | Checks that the boolean is true. Use for validating arguments to methods. 检查boolean是否是true. 用来验证方法参数 |
IllegalArgumentException |
checkNotNull(T) | Checks that the value is not null. Returns the value directly, so you can use checkNotNull(value) inline. 检查值是否是null. 方法直接这个值,所以你可以直接在行内使用checkNotNull(value) |
NullPointerException |
checkState(boolean) | Checks some state of the object, not dependent on the method arguments. For example, an Iterator might use this to check that next has been called before any call to remove. 检查对象的状态, 它不依赖于方法参数. 例如, Iterator可能会用这个方法来检查next是否在remove之前调用 |
IllegalStateException |
checkElementIndex(int index, int size) | Checks that index is a valid element index into a list, string, or array with the specified size. An element index may range from 0 inclusive to size exclusive. You don't pass the list, string, or array directly; you just pass its size. 检查index是否是一个合法的长度为size的list,string,array的element index.element index的范围从0(包括)到size(不包括).你不需要直接传list,string,array,只要传他们的ize 返回index |
IndexOutOfBoundsException |
checkPositionIndex(int index, int size) | Checks that index is a valid position index into a list, string, or array with the specified size. A position index may range from 0 inclusive to size inclusive. You don't pass the list, string, or array directly; you just pass its size. 检查index是否是一个合法的长度为size的list.string.array的position index.position index的范围从0(包括)到size(包括).你不需要直接传list,string,array,只需要传他们的size |
IndexOutOfBoundsException |
checkPositionIndexes(int start, int end, int size) | Checks that [start, end) is a valid sub range of a list, string, or array with the specified size. Comes with its own error message. 检查[start, end)是否是一个长度为size的list,string,array的子范围. |
IndexOutOfBoundsException |
We preferred rolling our own preconditions checks over e.g. the comparable utilities from Apache Commons for a few reasons. Piotr Jagielski discusses why he prefers our utilities, but briefly:
因为某些原因,我们更建议使用我们的preconditions而不是使用Apache Commons 的 comparable工具. Piotr Jagielski 讨论了 为什么他愿意这么做, 简要的说一下原因:
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.
我们推荐你切分preconditions到不同的行中,这样可以帮助你在debug时找出哪个precondition失败了. 另外, 你应该提供有用的错误信息, 这样当每个check在他自己的行上时更容易确认错误所在.