如何在运行时检查子类是否是类的实例? [英] How to check if a subclass is an instance of a class at runtime?

查看:124
本文介绍了如何在运行时检查子类是否是类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何在运行时检查子类是否是类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆