craesh craesh - 1 year ago 102
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

. The same applies for other non-derived classes. But how do I check derived classes? E.g.
as subclass of
. I can't find any
method. Do I need to walk through all
and find my supeclass by my own?

Answer Source

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.



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;


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);


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