问题描述
我正在尝试使用 Java 的反射 API 并尝试处理一些字段.现在我坚持要确定我的字段的类型.字符串很简单,只需执行myField.getType().equals(String.class)
.这同样适用于其他非派生类.但是如何检查派生类呢?例如.LinkedList
作为 List
的子类.我找不到任何 isSubclassOf(...)
或 extends(...)
方法.我是否需要遍历所有 getSuperClass()
并自己找到我的超类?
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);
一般情况下,List
(上面)应该替换为 superclass
,myClass
应该替换为 subclass
>
where in general, List
(above) should be replaced with superclass
and myClass
should be replaced with subclass
来自 JavaDoc:
确定此 Class
对象表示的类或接口是否与指定的 Class
对象表示的类或接口相同,或者是其超类或超接口> 参数.如果是,则返回 true
;否则返回false
.如果这个 Class
对象表示一个原始类型,如果指定的 Class
参数正是这个 Class
,则此方法返回 true
目的;否则返回false
.
参考:
相关:
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 中另一个类对象的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!