检查类是否是Java中另一个类的子类 [英] Check if a class is subclass of another class in Java
问题描述
我正在玩Java的反射API,试图处理一些字段。现在我困惑于确定我的字段的类型。字符串很容易,只需做 myField.getType()。equals(String.class)
。这同样适用于其他非派生类。但是如何检查派生类?例如。 LinkedList
作为 List
的子类。我找不到任何 isSubclassOf(...)
或 extend(...)
方法。我需要遍历所有 getSuperClass()
,并自己找到我的supeclass吗?
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?
推荐答案
您需要此方法:
boolean isList = List.class.isAssignableFrom(myClass);
从 JavaDoc :
确定由此
Class
对象表示的类或接口是否与由指定的<$ c $>表示的类或接口相同,或者是类或接口的超类或超接口c> Class 参数。它返回true
如果是这样;否则返回false
。如果Class
对象表示一个原始类型,如果指定的Class
参数就是这个类
object;否则返回false
。
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
.
Class.isAssignableFrom(Class)
相关:
a)检查对象是否是编译时知道的类或接口(包括子类)的实例:
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)检查一个对象是否是一个只有知道的类或接口在运行时:
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);
}
这篇关于检查类是否是Java中另一个类的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!