Guide to Guava’s PreConditions – 番石榴指南》(Guava’s PreConditions

最后修改: 2017年 2月 6日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll show how to use the Google Guava’s Preconditions class.

在本教程中,我们将展示如何使用Google Guava的Preconditions类。

The Preconditions class provides a list of static methods for checking that a method or a constructor is invoked with valid parameter values. If a precondition fails, a tailored exception is thrown.

Preconditions类提供了一个静态方法列表,用于检查一个方法或构造函数是否以有效参数值被调用。如果一个前提条件失败,就会抛出一个量身定做的异常。

2. Google Guava’s Preconditions

2.Google Guava的前提条件

Each static method in the Preconditions class has three variants:

Preconditions类中的每个静态方法有三个变体。

  • No arguments. Exceptions are thrown without an error message
  • An extra Object argument acting as an error message. Exceptions are thrown with an error message
  • An extra String argument, with an arbitrary number of additional Object arguments acting as an error message with a placeholder. This behaves a bit like printf, but for GWT compatibility and efficiency it only allows %s indicators

Let’s have a look at how to use the Preconditions class.

让我们看一下如何使用Preconditions类。

2.1. Maven Dependency

2.1.Maven的依赖性

Let’s start by adding Google’s Guava library dependency in the pom.xml:

让我们先在pom.xml中加入Google的Guava库依赖。

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

The latest version of the dependency can be checked here.

最新版本的依赖关系可以在这里查看

3. checkArgument

3.checkArgument

The method checkArgument of the Preconditions class ensures the truthfulness of the parameters passed to the calling method. This method accepts a boolean condition and throws an IllegalArgumentException when the condition is false.

方法checkArgumentPreconditions类确保传递给调用方法的参数的真实性。该方法接受一个布尔条件,当条件为假时抛出一个IllegalArgumentException

Let’s see how we can use this method with some examples.

让我们通过一些例子来看看我们如何使用这种方法。

3.1. Without an Error Message

3.1.没有错误信息

We can use checkArgument without passing any extra parameter to the checkArgument method:

我们可以使用checkArgument,而不用向checkArgument方法传递任何额外的参数。

@Test
public void whenCheckArgumentEvaluatesFalse_throwsException() {
    int age = -18;
 
    assertThatThrownBy(() -> Preconditions.checkArgument(age > 0))
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessage(null).hasNoCause();
}

3.2. With an Error Message

3.2.带有错误信息

We can get a meaningful error message from the checkArgument method by passing an error message:

我们可以通过传递错误信息,从checkArgument方法中获得一个有意义的错误信息。

@Test
public void givenErrorMsg_whenCheckArgEvalsFalse_throwsException() {
    int age = -18;
    String message = "Age can't be zero or less than zero.";
 
    assertThatThrownBy(() -> Preconditions.checkArgument(age > 0, message))
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessage(message).hasNoCause();
}

3.3. With a Template Error Message

3.3.带有模板错误信息

We can get a meaningful error message along with dynamic data from the checkArgument method by passing an error message:

我们可以通过传递错误信息,从checkArgument方法中获得一个有意义的错误信息和动态数据。

@Test
public void givenTemplateMsg_whenCheckArgEvalsFalse_throwsException() {
    int age = -18;
    String message = "Age should be positive number, you supplied %s.";
 
    assertThatThrownBy(
      () -> Preconditions.checkArgument(age > 0, message, age))
      .isInstanceOf(IllegalArgumentException.class)
      .hasMessage(message, age).hasNoCause();
}

4. checkElementIndex

4.checkElementIndex

The method checkElementIndex checks that an index is a valid index in a list, string or an array of a specified size. An element index may range from 0 inclusive to size exclusive. You don’t pass a list, string or array directly, you just pass its size. This method throws an IndexOutOfBoundsException if the index is not a valid element index, else it returns an index that’s being passed to the method.

方法checkElementIndex检查一个索引是否是一个列表、字符串或指定大小的数组中的有效索引。一个元素索引的范围可以从0(包括)到大小不限。你不需要直接传递一个列表、字符串或数组,你只需要传递它的大小。如果索引不是一个有效的元素索引,这个方法会抛出一个IndexOutOfBoundsException,否则它会返回一个被传递给该方法的索引。

Let’s see how we can use this method by showing a meaningful error message from the checkElementIndex method by passing an error message when it throws an exception:

让我们看看我们如何使用这个方法,当checkElementIndex方法抛出异常时,通过传递错误信息来显示一个有意义的错误信息。

@Test
public void givenArrayAndMsg_whenCheckElementEvalsFalse_throwsException() {
    int[] numbers = { 1, 2, 3, 4, 5 };
    String message = "Please check the bound of an array and retry";
 
    assertThatThrownBy(() -> 
      Preconditions.checkElementIndex(6, numbers.length - 1, message))
      .isInstanceOf(IndexOutOfBoundsException.class)
      .hasMessageStartingWith(message).hasNoCause();
}

5. checkNotNull

5.checkNotNull

The method checkNotNull checks whether a value supplied as a parameter is null. It returns the value that’s been checked. If the value that has been passed to this method is null, then a NullPointerException is thrown.

方法checkNotNull检查作为参数提供的值是否为空。它返回被检查的值。如果传递给该方法的值是空的,那么会抛出一个NullPointerException

Next, we are going to show how to use this method by showing how to get a meaningful error message from the checkNotNull method by passing an error message:

接下来,我们将展示如何使用这个方法,通过传递错误信息,从checkNotNull方法中获得一个有意义的错误信息。

@Test
public void givenNullString_whenCheckNotNullWithMessage_throwsException () {
    String nullObject = null;
    String message = "Please check the Object supplied, its null!";
 
    assertThatThrownBy(() -> Preconditions.checkNotNull(nullObject, message))
      .isInstanceOf(NullPointerException.class)
      .hasMessage(message).hasNoCause();
}

We can also get a meaningful error message based on dynamic data from the checkNotNull method by passing a parameter to the error message:

我们还可以通过向错误信息传递一个参数,从checkNotNull方法中获得一个基于动态数据的有意义的错误信息。

@Test
public void whenCheckNotNullWithTemplateMessage_throwsException() {
    String nullObject = null;
    String message = "Please check the Object supplied, its %s!";
 
    assertThatThrownBy(
      () -> Preconditions.checkNotNull(nullObject, message, 
        new Object[] { null }))
      .isInstanceOf(NullPointerException.class)
      .hasMessage(message, nullObject).hasNoCause();
}

6. checkPositionIndex

6.checkPositionIndex

The method checkPositionIndex checks that an index passed as an argument to this method is a valid index in a list, string or array of a specified size. A position index may range from 0 inclusive to size inclusive. You don’t pass the list, string or array directly, you just pass its size.

方法checkPositionIndex检查作为参数传递给该方法的索引是否是指定大小的列表、字符串或数组中的一个有效索引。一个位置索引的范围可以从0(包括)到大小(包括)。你不需要直接传递列表、字符串或数组,你只需要传递它的大小。

This method throws an IndexOutOfBoundsException if the index passed is not between 0 and the size given, else it returns the index value.

如果传递的索引不在0和给定的大小之间,这个方法会抛出一个IndexOutOfBoundsException,否则会返回索引值。

Let’s see how we can get a meaningful error message from the checkPositionIndex method:

让我们看看如何从checkPositionIndex方法中获得一个有意义的错误信息。

@Test
public void givenArrayAndMsg_whenCheckPositionEvalsFalse_throwsException() {
    int[] numbers = { 1, 2, 3, 4, 5 };
    String message = "Please check the bound of an array and retry";
 
    assertThatThrownBy(
      () -> Preconditions.checkPositionIndex(6, numbers.length - 1, message))
      .isInstanceOf(IndexOutOfBoundsException.class)
      .hasMessageStartingWith(message).hasNoCause();
}

7. checkState

7.checkState

The method checkState checks the validity of the state of an object and is not dependent on the method arguments. For example, an Iterator might use this to check that next has been called before any call to remove. This method throws an IllegalStateException if the state of an object (boolean value passed as an argument to the method) is in an invalid state.

方法checkState检查对象的状态的有效性,并且不依赖于方法的参数。例如,一个迭代器可以使用这个方法来检查在调用移除之前是否已经调用了next。如果一个对象的状态(作为参数传递给方法的布尔值)处于无效状态,该方法会抛出一个IllegalStateException

Let’s see how we can use this method by showing a meaningful error message from the checkState method by passing an error message when it throws an exception:

让我们看看我们如何使用这个方法,当checkState方法抛出异常时,通过传递错误信息来显示一个有意义的错误信息。

@Test
public void givenStatesAndMsg_whenCheckStateEvalsFalse_throwsException() {
    int[] validStates = { -1, 0, 1 };
    int givenState = 10;
    String message = "You have entered an invalid state";
 
    assertThatThrownBy(
      () -> Preconditions.checkState(
        Arrays.binarySearch(validStates, givenState) > 0, message))
      .isInstanceOf(IllegalStateException.class)
      .hasMessageStartingWith(message).hasNoCause();
}

8. Conclusion

8.结论

In this tutorial, we illustrated the methods of the PreConditions class from the Guava library. The Preconditions class provides a collection of static methods that are used to validate that a method or a constructor is invoked with valid parameter values.

在本教程中,我们说明了Guava库中的PreConditions类的方法。Preconditions类提供了一系列静态方法,用于验证一个方法或构造函数被调用时的有效参数值。

The code belonging to the above examples can be found in the GitHub project – this is a Maven-based project, so it should be easy to import and run as is.

属于上述例子的代码可以在GitHub项目中找到–这是一个基于Maven的项目,所以应该很容易导入并按原样运行。