Basic|Basic Guava Utilities-Preconditions
Preconditions类包含有许多的静态方法来检查代码的状态。
你可以自己来实现预置的条件判断,像下面的代码段:
if(someObj == null){
throw new IllegalArgumentException(" someObj must not be null");
}
但是,使用Precondition(静态导入)类来实现同样的功能,相当的简洁:
checkNotNull(someObj,"someObj must not be null");
下面是Precondition类的几种常用方法示例:
public class PreconditionExample {
private String label;
private int[] values = new int[5];
private int currentIndex;
public PreconditionExample(String label) {
//returns value of object if not null
this.label = checkNotNull(label,"Label can''t be null");
}public void updateCurrentIndexValue(int index, int valueToSet) {
//Check index valid first
this.currentIndex = checkElementIndex(index, values.length,"Index out of bounds for values");
//Validate valueToSet
checkArgument(valueToSet <= 100,"Value can't be more than 100");
values[this.currentIndex] = valueToSet;
}public void doOperation(){
checkState(validateObjectState(),"Can't perform operation");
}private boolean validateObjectState(){
return this.label.equalsIgnoreCase("open") && values[this.currentIndex]==10;
}
}
【Basic|Basic Guava Utilities-Preconditions】上面代码中四个Precondition类中方法的简介:
- checkNotNull (T object, Object message): 如果object不为空,直接返回object;否则,抛出NullPointerException异常。
- checkElementIndex (int index, int size, Object message): 如果index的值在给定的数组、集合和字符的长度size范围之类,则返回index;否则,抛出IndexOutOfBoundsException异常。
- checkArgument (Boolean expression, Object message): 此方法接受一个返回值为boolean类型的expression表达式,如果表达式不为true,则抛出IllegalArgumentException异常。
- checkState (Boolean expression, Object message):同checkArgument
推荐阅读
- Vapor文档学习卅八:|Vapor文档学习卅八: TESTING - Basic
- |NO.Z.00025|——————————|LinuxBasicEnd|——|Linux&软件包安装.V04|
- |NO.Z.00000|——————————|LinuxBasicEnd|
- |NO.Z.00028|——————————|LinuxBasicEnd|——|Linux&软件包安装.V07|——|源码安装|
- |NO.Z.00027|——————————|LinuxBasicEnd|——|Linux&软件包安装.V06|——|rpm在线|本地YUM|
- |NO.Z.00001|——————————|LinuxBasicEnd|——|Linux&行业介绍|
- |NO.Z.00005|——————————|LinuxBasicEnd|——|Linux&目录结构.V2|
- |NO.Z.00002|——————————|LinuxBasicEnd|——|Linux&基础知识|
- YepBasic|4.DesignForShapes\CreateAutoShape(ShieldGnd)
- 使用nginx的auth_basic实现prometheus 安全认证