What is Validate.isInstanceOf() in Java?

Overview

isInstanceOf() is a staticthe methods in Java that can be called without creating an object of the class. method of the 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.

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-lang package, refer to the Maven Repository.

You can import the Validate class as follows:

import org.apache.commons.lang3.Validate;

Syntax

public static void isInstanceOf(final Class<?> type, final Object obj, final String message, final Object... values)

Parameters

  • 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.

Return value

This method does not return anything.

Code

import org.apache.commons.lang3.Validate;
public class Main{
public static void main(String[] args){
// Example 1
double doubleToValidate = 234322343;
Validate.isInstanceOf(Double.class, doubleToValidate);
// Example 2
String exceptionMessageFormat = "Argument not an instance of the given class";
Validate.isInstanceOf(String.class, doubleToValidate, exceptionMessageFormat);
}
}

Output

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)

Example 1

  • Class to validate against - Double
  • Double value = 234322343

The method does not throw an exception, as the input value is an instance of the given class.

Example 2

  • Class to validate against - String
  • double value = 234322343
  • exception message = "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.

Free Resources