如何在运行时检查子类是否是类的实例?
在Android应用程序测试套件中,我有一个这样的类,其中 B
是一个视图:
In an android app test suite I have a class like this where B
is a view:
public class A extends B {
... etc...
}
现在我有一个视图对象列表,其中可能包含 A
对象,但在这种情况下我只关心它们是子类还是实例 B
。我想做类似的事情:
now I have a list of view objects which may contain A
objects but in this case I only care if they're subclasses or "instances of" B
. I'd like to do something like:
ArrayList<View> viewList = getViews();
Iterator<View> iterator = viewList.iterator();
while (iterator.hasNext() && viewList != null) {
View view = iterator.next();
if (view.getClass().isInstance(B.class)) {
// this is an instance of B
}
}
问题是如果
遇到 A
对象不评估为code> B 的实例。有没有办法 isSubclassOf
还是什么?
The problem is that when the if
encounters an A
object it doesn't evaluate to an "instance of B
". Is there a way to do isSubclassOf
or something?
你有仔细阅读此方法的API。有时候你很容易感到困惑。
You have to read the API carefully for this methods. Sometimes you can get confused very easily.
它是:
if (B.class.isInstance(view))
API说:确定指定的对象 (参数)与此类 (您调用方法的类对象)所代表的对象分配兼容
API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)
或:
if (B.class.isAssignableFrom(view.getClass()))
API说:确定此类所代表的类或接口类对象与指定的Class参数
API says: 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
或(没有反思和推荐的):
or (without reflection and the recommend one):
if (view instanceof B)