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?
You want this method:
boolean isList = List.class.isAssignableFrom(myClass);
where in general, List
(above) should be replaced with superclass
and myClass
should be replaced with subclass
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 specifiedClass
parameter. It returnstrue
if so; otherwise it returnsfalse
. If thisClass
object represents a primitive type, this method returnstrue
if the specifiedClass
parameter is exactly thisClass
object; otherwise it returnsfalse
.
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);
}