Checking Type Relationships with isAssignableFrom
You'll learn how to programmatically determine if one class can be assigned to another using reflection.
What Is isAssignableFrom()?
The isAssignableFrom() method on a Class object answers the question: "Can objects of this type be assigned from objects of that type?" In simpler terms, it checks whether one class is a superclass or superinterface of another class at runtime.
Think of it like asking: "Is this container compatible with that content?" If you have a variable of type Animal, can you assign a Dog instance to it? isAssignableFrom() gives you the answer programmatically.
How It Works
The method signature is:
boolean isAssignableFrom(Class<?> cls)
You call it on the target type (the variable type) and pass the source type (the value type). It returns true if the assignment is valid.
The relationship:
- Returns
trueif the calling class is the same as, a superclass of, or a superinterface of the parameter class - Returns
trueif both represent the same class or interface
Practical Example
Class<?> animalClass = Animal.class;
Class<?> dogClass = Dog.class;
Class<?> stringClass = String.class;
// Can an Animal variable hold a Dog? Yes!
boolean result1 = animalClass.isAssignableFrom(dogClass); // true
// Can a Dog variable hold any Animal? No!
boolean result2 = dogClass.isAssignableFrom(animalClass); // false
// Can an Animal variable hold a String? No!
boolean result3 = animalClass.isAssignableFrom(stringClass); // false
This is particularly useful when writing generic frameworks or libraries that need to validate type compatibility at runtime.
Key Takeaway: Use isAssignableFrom() to check if one class can hold instances of another class—the calling class is the "container," and the parameter is the "content."