isInstanceOf()
is a Validate
class which is used to check whether the given object is an instance of the given class. If the object is not an instance of the given class, then the method throws an exception.
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 isInstanceOf(final Class<?> type, final Object obj, final String message, final Object... values)
final Class<?> type
: The class the object must be an instance of.
final Object obj
: The object to check.
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{public static void main(String[] args){// Example 1double doubleToValidate = 234322343;Validate.isInstanceOf(Double.class, doubleToValidate);// Example 2String exceptionMessageFormat = "Argument not an instance of the given class";Validate.isInstanceOf(String.class, doubleToValidate, exceptionMessageFormat);}}
The output of the code will be as follows:
Exception in thread "main" java.lang.IllegalArgumentException: Argument not an instance of the given class
at org.apache.commons.lang3.Validate.isInstanceOf(Validate.java:1275)
at Main.main(Main.java:12)
Double
234322343
The method does not throw an exception, as the input value is an instance of the given class.
String
234322343
"Argument not an instance of the given class"
The method throws an IllegalArgumentException
exception with the exception message Argument not an instance of the given class
, as the input value is not an instance of the given class.