What is Validate.validState() in Java?
validState() is a Validate class that is used to check whether the specified boolean expression evaluates to true or not. If the expression results in false, the method throws an exception with a specified message.
How to import Validate
The definition of Validate can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the Validate class as follows:
import org.apache.commons.lang3.Validate;
Syntax
public static void validState(final boolean expression, final String message, final Object... values)
Parameters
-
final boolean expression: Thebooleanexpression to evaluate. -
final String message: The exception message. -
final Object... values: The optional values for the formatted exception message.
Return value
This method does not return anything.
Code
import org.apache.commons.lang3.Validate;public class Main{static class Status{private boolean flag;public Status(boolean flag) {this.flag = flag;}public boolean isFlag() {return flag;}}public static void main(String[] args){// Example 1Status status = new Status(true);Validate.validState(status.isFlag());// Example 2String exceptionMessage = "Object State not OK!!";status = new Status(false);Validate.validState(status.isFlag(), exceptionMessage);}}
Output
The output of the code will be as follows:
Exception in thread "main" java.lang.IllegalStateException: Object State not OK!!
at org.apache.commons.lang3.Validate.validState(Validate.java:816)
at Main.main(Main.java:25)
Explanation
In the code above, we define a class Status that has a boolean attribute called flag.
Example 1
In the first example, we create an instance of the Status class with the flag value as true.
Then, we pass the isFlag() method as the argument to the validState() method. The method does not throw an exception, as the isFlag() method evaluates to true.
Example 2
In the second example, we create an instance of the Status class with the flag value as false.
Then we pass the isFlag() method as the argument to the validState() method.
The method throws an IllegalStateException exception with Object State not OK!! as the exception message, as the isFlag() method evaluates to false.