Assert

Origin

The assert keyword exists in Java, but there are many problems with it:

  1. The assert keyword needs to be explicitly enabled at runtime to take effect, otherwise your assertions are meaningless.
  2. Using assert as a replacement for if is a pitfall. The judgment of assert is similar to that of if statements, but the roles of the two are fundamentally different: the assert keyword is intended for use during testing and debugging of programs. However, if you accidentally use assert to control the program’s business logic, removing the assert keyword after testing and debugging is complete means modifying the program’s normal logic.
  3. If an assertion fails, the program will exit.

Therefore, it is not recommended to use this keyword. Correspondingly, in Hutool, a more friendly Assert class is encapsulated for assertion determination.

Introduction

The Assert class is more like the Assert class in Junit or the Preconditions in Guava. Its main function is to verify the validity of parameters anywhere in the method. When the assertion condition is not met, it will throw IllegalArgumentException or IllegalStateException exceptions.

Usage

String a = null;
cn.hutool.lang.Assert.isNull(a);

More methods

  • isTrue: Whether it is true
  • isNull: Whether it is a null value, if not null, an exception will be thrown
  • notNull: Whether it is not null
  • notEmpty: Whether it is not empty
  • notBlank: Whether it is not a blank character
  • notContain: Whether it is a substring
  • notEmpty: Whether it is not empty
  • noNullElements: Whether the array contains null elements
  • isInstanceOf: Whether it is an instance of a class
  • isAssignable: Whether it is a subclass-superclass relationship
  • state: It will throw an IllegalStateException exception