Google Guava中提供了一个Preconditions类,用于校验入参的正确性
源码分析:
//检查参数(expression)是否合法,若为false,抛出IllegalArgumentException异常
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
//检查入参,带异常信息
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
//检查入参,errorMessageTemplate表示异常信息模板,errorMessageArgs将被替换为信息模板中的参数
public static void checkArgument(
boolean expression,
@Nullable String errorMessageTemplate,
@Nullable Object... errorMessageArgs) {
if (!expression) {
throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs));
}
}
示例如下:
示例1:
import com.google.common.base.Preconditions;
public class PreconditionsDemo {
public static void main(String args[]) {
boolean demo=5<0;
Preconditions.checkArgument(demo);
}
}
输出:
Exception in thread "main" java.lang.IllegalArgumentException
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:108)
at demo.PreconditionsDemo.main(PreconditionsDemo.java:8)
示例2:
import com.google.common.base.Preconditions;
public class PreconditionsDemo {
public static void main(String args[]) {
boolean demo=5<0;
Preconditions.checkArgument(demo,"demo不能为false");
}
}
输出:
Exception in thread "main" java.lang.IllegalArgumentException: demo不能为false
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:122)
at demo.PreconditionsDemo.main(PreconditionsDemo.java:8)
示例3:
import com.google.common.base.Preconditions;
public class PreconditionsDemo {
public static void main(String args[]) {
boolean demo=5<0;
Preconditions.checkArgument(demo,"该参数为%s",demo);
}
}
输出:
Exception in thread "main" java.lang.IllegalArgumentException: 该参数为false
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:191)
at demo.PreconditionsDemo.main(PreconditionsDemo.java:8)
示例4:
import com.google.common.base.Preconditions;
public class PreconditionsDemo {
public static void main(String args[]) {
boolean demo=5<0;
Preconditions.checkArgument(demo,"%s为%s","demo",demo);
}
}
输出:
Exception in thread "main" java.lang.IllegalArgumentException: demo为false
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:383)
at demo.PreconditionsDemo.main(PreconditionsDemo.java:8)
类似的方法还有:
检查入参状态的checkState()方法,参数为false将抛出IllegalStateException异常;检查入参是否为空的checkNotNull()方法,参数为null将抛出NullPointException异常;检查数组索引是否越界,越界将抛出IndexOutOfBoundsException异常,用法与checkArgument类似,检查数组是否越界稍微有点不同,具体可以查看源码,很好理解