如何在运行时检查子类是否是类的实例?
在 android 应用程序测试套件中,我有一个这样的类,其中 B
是一个视图:
public class A extends B {
... etc...
}
现在我有一个视图对象列表,其中可能包含 A
对象,但在本例中我只关心它们是否是 B
的子类或“实例”。我想做类似的事情:
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
}
}
问题是,当 if
遇到 A
对象时,它不会计算为“B
实例”代码>”。有没有办法做 isSubclassOf
之类的事情?
In an android app test suite I have a class like this where B
is a view:
public class A extends B {
... etc...
}
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
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您必须仔细阅读此方法的 API。有时你很容易感到困惑。
它是:
API 表示:确定指定的对象(参数)是否与这个类表示的对象赋值兼容 >(您调用方法的类对象)
或:
API 表示:确定此 Class 对象 表示的类或接口是否与以下对象相同,或者是超类或由指定的 Class 参数表示的类或接口的超接口
或(无反射和推荐的):
You have to read the API carefully for this methods. Sometimes you can get confused very easily.
It is either:
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)
or:
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 recommended one):
如果 view 是 B 或 A 子类(或 B 的任何子类)的实例,则返回 true。
This will return true if view is an instance of B or the subclass A (or any subclass of B for that matter).
也许我错过了一些东西,但这还不够:
Maybe I'm missing something, but wouldn't this suffice:
类.isAssignableFrom()
- 也适用于接口。如果您不希望这样,则必须调用getSuperclass()
并测试,直到到达Object
。Class.isAssignableFrom()
- works for interfaces as well. If you don't want that, you'll have to callgetSuperclass()
and test until you reachObject
.反之亦然:
B.class.isInstance(view)
It's the other way around:
B.class.isInstance(view)
如果存在多态性,例如检查 SQLRecoverableException 与 SQLException,可以这样做。
简单地说,
If there is polymorphism such as checking SQLRecoverableException vs SQLException, it can be done like that.
Simply say,
我从未真正使用过这个,但尝试
view.getClass().getGenericSuperclass()
I've never actually used this, but try
view.getClass().getGenericSuperclass()