JAVA判空,采用if…else…的方式,冗长。最近在看源代码,看到一些写法很好。
checkState
package com.google.common.base;
public final class Preconditions {
// 判断expression是否为真,如果不为true,抛出一个异常 IllegalStateException
public static void checkState(boolean expression, @Nullable Object errorMessage)
}
由于IllegalStateException 继承自RuntimeException,所以使用checkState的方法签名,不需要定义throws,但是在合适的地方,把这个异常catch住最好。
这个方法被大量重载,有各种变形。
另外这个类里面,还有checkArgument,区别是后者抛出的是IllegalArgumentException。
还有checkNotNull,抛出的是NullPointerException
还有checkElementIndex,用来判断类似数组边界。抛出IndexOutOfBoundsException
(数组边界都可以这么方便地判断,真贴心啊。。。)
verify.java
Ensures that expression is true, throwing a VerifyException with a custom message otherwise.
See verify(boolean, String, Object...) for details.
Since:
23.1 (varargs overload since 17.0)
public static void verify(
boolean expression, @Nullable String errorMessageTemplate, int p1, @Nullable Object p2)