前置条件:让方法调用的前置条件判断更简单。
没有额外参数:抛出的异常中没有错误消息;
有一个object对象作为额外参数:抛出的异常使用object.tostring() 作为错误消息;
有一个string对象作为额外参数,并且有一组任意数量的附加object对象:这个变种处理异常消息的方式有点类似printf,但考虑gwt的兼容性和效率,只支持%s指示符。例如:
<code>1</code>
<code>checkargument(i >= </code><code>0</code><code>, </code><code>"argument was %s but expected nonnegative"</code><code>, i);</code>
<code>2</code>
<code>checkargument(i < j, </code><code>"expected i < j, but %s > %s"</code><code>, i, j);</code>
<b>方法声明(不包括额外参数)</b><b></b>
<b>描述</b><b></b>
<b>检查失败时抛出的异常</b><b></b>
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkargument(boolean)">checkargument(boolean)</a>
检查boolean是否为true,用来检查传递给方法的参数。
illegalargumentexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checknotnull(t)">checknotnull(t)</a>
检查value是否为null,该方法直接返回value,因此可以内嵌使用checknotnull。
nullpointerexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkstate(boolean)">checkstate(boolean)</a>
用来检查对象的某些状态。
illegalstateexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkelementindex(int,%20int)">checkelementindex(int index, int size)</a>
检查index作为索引值对某个列表、字符串或数组是否有效。index>=0 && index<size *
indexoutofboundsexception
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkpositionindex(int,%20int)">checkpositionindex(int index, int size)</a>
检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 && index<=size *
<a href="http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/base/preconditions.html#checkpositionindexes(int,%20int,%20int)">checkpositionindexes(int start, int end, int size)</a>
检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效*
译者注:
*索引值常用来查找列表、字符串或数组中的元素,如list.get(int), string.charat(int)
*位置值和位置范围常用来截取列表、字符串或数组,如list.sublist(int,int), string.substring(int)
在静态导入后,guava方法非常清楚明晰。checknotnull清楚地描述做了什么,会抛出什么异常;
checknotnull直接返回检查的参数,让你可以在构造函数中保持字段的单行赋值风格:this.field = checknotnull(field)
在编码时,如果某个值有多重的前置条件,我们建议你把它们放到不同的行,这样有助于在调试时定位。此外,把每个前置条件放到不同的行,也可以帮助你编写清晰和有用的错误消息。