craesh craesh - 4 months ago 43
Java Question

Check if a class is subclass of another class in Java

I'm playing around with Java's reflection API and trying to handle some fields. Now I'm stuck with identifying the type of my fields. Strings are easy, just do

myField.getType().equals(String.class)
. The same applies for other non-derived classes. But how do I check derived classes? E.g.
LinkedList
as subclass of
List
. I can't find any
isSubclassOf(...)
or
extends(...)
method. Do I need to walk through all
getSuperClass()
and find my supeclass by my own?

Answer

You want this method:

boolean isList = List.class.isAssignableFrom(myClass);

From the JavaDoc:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

Reference:


Related:

a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:

boolean isInstance = someObject instanceof SomeTypeOrInterface;

Example:

assertTrue(Arrays.asList("a", "b", "c") instanceof List<?>);

b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:

Class<?> typeOrInterface = // acquire class somehow
boolean isInstance = typeOrInterface.isInstance(someObject);

Example:

public boolean checkForType(Object candidate, Class<?> type){
    return type.isInstance(candidate);
}
Comments