其他分享
首页 > 其他分享> > 使用Goole Guava中的Preconditions类,让你的代码更加优雅简洁!!!

使用Goole Guava中的Preconditions类,让你的代码更加优雅简洁!!!

作者:互联网

Preconditions类,让你的代码更加优雅简洁!!!

最近发现一个非常好用的类库,那就是Java的Google核心库Guava。其中包括新的集合类型(例如多图和多集),不可变的集合,图形库以及用于并发,I / O,哈希,缓存,基元,字符串等的实用程序。今天先来说说guava.common.base下的Preconditions类,让我们的代码变得更加的优雅简洁。

我们为什么说Preconditions类让我们的代码变得更加的优雅简洁了呢???
那是因为在项目开发中,往往我们后台对于前端传过来的参数就需要进行判空,如果参数有问题就应该抛出异常,平常我们都是使用if来进行判断,如果当判断的参数比较多时,就会重复使用if,不仅编码复杂了,而且可读性也变得差了,代码看起来也不简洁优雅。
这个时候我们使用Preconditions类就可以很好地解决上面的问题,Preconditions类就是对这个判空的方法进行了封装,让我们使用起来方便,从而让我们的代码代码看起来也就变得优雅了不少。

使用Preconditions类之前当然首先应该导入它的依赖

<!-- maven导入方式 -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.0.1-jre</version>
</dependency>

checkArgument(boolean expression)

检查表达式是否非法参数,用于非法参数异常
源码如下:

//直接非法参数异常
public static void checkArgument(boolean expression) {
    //如果expression的表达式不成立,抛出非法参数异常
    if (!expression) {
      throw new IllegalArgumentException();
    }
  }

//抛出非法参数异常的时候,可以对抛出的异常进行说明
public static void checkArgument(boolean expression, @Nullable Object errorMessage) {
    if (!expression) {
      throw new IllegalArgumentException(String.valueOf(errorMessage));
    }
  }

使用方法

String a = "";
//"参数不能为空"  
Preconditions.checkArgument( !"".equals(a),"参数不能为空" );

//expression表达式还可以这样的方式写,可以搭配&&、|| 逻辑运算符,或者使用equals方法进行判断
Preconditions.checkArgument(args != null && arg != null );

checkNotNull(T reference)

检查参数是否为空,抛出空指针异常NullPointerException()
源码如下:

	@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;
        }
    }

使用:

Object obj = null;
//判断参数是否为空  直接传人任意类型的变量,错误信息
Preconditions.checkNotNull(obj,"对象不能为空");

checkArgument()和checkNotNull()两种方法在项目中灵活使用进行判断,可以让代码避免连串的if-else语句,造成代码复杂繁多,使用这2个方法进行判断就能很好的解决此问题。

checkElementIndex(int index, int size)、checkPositionIndex(int index, int size)

检查index是否为在一个长度为size的list, string或array合法的范围。 index的范围区间是[0, size)(包含0不包含size)。无需直接传入list, string或array, 只需传入大小,返回index。失败时抛出的异常IndexOutOfBoundsException。
源码如下:

	@CanIgnoreReturnValue
    public static int checkElementIndex(int index, int size) {
        return checkElementIndex(index, size, "index");
    }

    @CanIgnoreReturnValue
    public static int checkElementIndex(int index, int size, @Nullable String desc) {
        if (index >= 0 && index < size) {
            return index;
        } else {
            throw new IndexOutOfBoundsException(badElementIndex(index, size, desc));
        }
    }

    private static String badElementIndex(int index, int size, @Nullable String desc) {
        if (index < 0) {
            return Strings.lenientFormat("%s (%s) must not be negative", new Object[]{desc, index});
        } else if (size < 0) {
            throw new IllegalArgumentException("negative size: " + size);
        } else {
            return Strings.lenientFormat("%s (%s) must be less than size (%s)", new Object[]{desc, index, size});
        }
    }

	@CanIgnoreReturnValue
    public static int checkPositionIndex(int index, int size) {
        return checkPositionIndex(index, size, "index");
    }

    @CanIgnoreReturnValue
    public static int checkPositionIndex(int index, int size, @Nullable String desc) {
        if (index >= 0 && index <= size) {
            return index;
        } else {
            throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc));
        }
    }

    private static String badPositionIndex(int index, int size, @Nullable String desc) {
        if (index < 0) {
            return Strings.lenientFormat("%s (%s) must not be negative", new Object[]{desc, index});
        } else if (size < 0) {
            throw new IllegalArgumentException("negative size: " + size);
        } else {
            return Strings.lenientFormat("%s (%s) must not be greater than size (%s)", new Object[]{desc, index, size});
        }
    }

使用如下:

int i = Preconditions.checkElementIndex(4, 5);
//4
System.out.println( i );
//java.lang.IndexOutOfBoundsException: index (5) must be less than size (5)
int j = Preconditions.checkElementIndex(5, 5);

//5
System.out.println(Preconditions.checkPositionIndex(5, 6));
//java.lang.IndexOutOfBoundsException: index (7) must not be greater than size (6)
Preconditions.checkPositionIndex(7,6);

checkPositionIndexes(int start, int end, int size)

检查[start, end)是否是一个长度为size的list, string或array合法的范围子集。失败时抛出异常IndexOutOfBoundsException。
源码如下:

	public static void checkPositionIndexes(int start, int end, int size) {
        if (start < 0 || end < start || end > size) {
            throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size));
        }
    }

    private static String badPositionIndexes(int start, int end, int size) {
        if (start >= 0 && start <= size) {
            return end >= 0 && end <= size ? Strings.lenientFormat("end index (%s) must not be less than start index (%s)", new Object[]{end, start}) : badPositionIndex(end, size, "end index");
        } else {
            return badPositionIndex(start, size, "start index");
        }
    }

使用如下:

//java.lang.IndexOutOfBoundsException: end index (7) must not be greater than size (5)
Preconditions.checkPositionIndexes(4,7,5);

checkElementIndex()/checkPositionIndex()/checkPositionIndexes()在项目中可以使用在list, string或array的一些取值赋值中,可以很好地避免下标越界的这么一个异常。

标签:index,end,int,Goole,Preconditions,new,Guava,size
来源: https://blog.csdn.net/weixin_45003796/article/details/112260018