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.
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-lang
package, refer to the Maven Repository.
You can import the Validate
class as follows:
import org.apache.commons.lang3.Validate;
public static void validState(final boolean expression, final String message, final Object... values)
final boolean expression
: The boolean
expression to evaluate.
final String message
: The exception message.
final Object... values
: The optional values for the formatted exception message.
This method does not return anything.
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);}}
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)
In the code above, we define a class Status
that has a boolean
attribute called flag
.
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
.
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
.