What is Validate.isAssignableFrom in Java?
isAssignableFrom() is a Validate class that is used to check whether a given class can be cast/converted to another specified class. If the conversion is not possible, 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-langpackage, refer to the Maven Repository.
You can import the Validate class as follows:
import org.apache.commons.lang3.Validate;
Syntax
public static void isAssignableFrom(final Class<?> superType, final Class<?> type, final String message, final Object... values)
Parameters
-
final Class<?> superType: The class to be validated against. -
final Class<?> type: The class to validate. -
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 1Integer integer = 342;Validate.isAssignableFrom(Object.class, integer.getClass());// Example 2String exceptionMessage = "The validated object can not be converted from %s class to %s class";integer = 342;Validate.isAssignableFrom(String.class, integer.getClass(), exceptionMessage, Integer.class.toString(), String.class.toString());}}
Output
The output of the code will be as follows:
Exception in thread "main" java.lang.IllegalArgumentException: The validated object can not be converted from class java.lang.Integer class to class java.lang.String class
at org.apache.commons.lang3.Validate.isAssignableFrom(Validate.java:1326)
at Main.main(Main.java:13)
Example 1
In the first example, we try to cast the integer object of the Integer class to the Object class. As Object is a super class of all classes in Java, the method does not throw an exception.
Example 2
In the second example, we try to cast the integer object of the Integer class to the String class. As String is not a super class of Integer class, the method throws an IllegalArgumentException exception with The validated object can not be converted from class java.lang.Integer class to class java.lang.String class as the exception message.