码迷,mamicode.com
首页 > 其他好文 > 详细

guava Preconditions

时间:2019-01-29 11:54:10      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:tin   ror   gear   message   pos   check   col   dex   null   

1.checkArgument

2.checkState

3.checkNotNull

4.checkElementIndex

5.checkPositionIndex

该类就这五种重载方法。

1. checkArgument   用作检查参数

1.1 单纯的判断表达式
public static void checkArgument(boolean expression) {
        if (!expression) {
            throw new IllegalArgumentException();
        }
}

1.2  规定表达式false 返回的错误信息
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
        if (!expression) {
            throw new IllegalArgumentException(String.valueOf(errorMessage));
        }
}
1.3 表达式, 错误模板, 错误信息
public static void checkArgument(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
        if (!expression) {
            throw new IllegalArgumentException(Strings.lenientFormat(errorMessageTemplate, errorMessageArgs));
        }
}

2. checkState   用作检查状态

  public static void checkState(boolean expression) {
        if (!expression) {
            throw new IllegalStateException();
        }
    }

    public static void checkState(boolean expression, @Nullable Object errorMessage) {
        if (!expression) {
            throw new IllegalStateException(String.valueOf(errorMessage));
        }
    }

    public static void checkState(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
        if (!expression) {
            throw new IllegalStateException(Strings.lenientFormat(errorMessageTemplate, errorMessageArgs));
        }
    }

3.checkNotNull    检查参数是否不为空

@CanIgnoreReturnValue
    public static <T> T checkNotNull(T reference) {
        if (reference == null) {
            throw new NullPointerException();
        } else {
            return reference;
        }
    }

    @CanIgnoreReturnValue
    public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
        if (reference == null) {
            throw new NullPointerException(String.valueOf(errorMessage));
        } else {
            return reference;
        }
    }

    @CanIgnoreReturnValue
    public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) {
        if (reference == null) {
            throw new NullPointerException(Strings.lenientFormat(errorMessageTemplate, errorMessageArgs));
        } else {
            return reference;
        }
    }

 

guava Preconditions

标签:tin   ror   gear   message   pos   check   col   dex   null   

原文地址:https://www.cnblogs.com/inspirationBoom/p/10333157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!