检查对象是否是类的实例(但不是其子类的实例) [英] Check if a object is a instance of a class (but not a instance of its subclass)
问题描述
对于此示例:
public class Foo{}
public class Bar extends Foo{}
....
void myMethod(Foo qux){
if (checkInstance(qux,Foo.class)){
....
}
}
如何检查 qux
是Foo的一个实例(但不是它的foo子类的实例)?那就是:
How can I check if qux
is a instance of Foo (but not a instance of its subclass of foo)? That is:
- checkInstance(qux,Foo.class)= true
- checkInstance(qux, Bar.class)= false
是否存在某种语句,例如 instanceof
这张支票?或者我应该使用 qux.getClass()。equals(Foo.class)
Is there some kind of statement like instanceof
for this check? or I should use qux.getClass().equals(Foo.class)
推荐答案
如果必须这样做,唯一的方法就是你建议的 getClass()。equals(Foo.class)
选项。
If you have to do this, the only way would be the getClass().equals(Foo.class)
option you've suggested.
但是,OO设计的目标是允许您以相同的方式处理任何 <$ em> c> Foo 。实例是否是子类在正常程序中应该是无关紧要的。
However, the goal of OO design is to allow you to treat any Foo
in the same fashion. Whether or not the instance is a subclass should be irrelevant in a normal program.
这篇关于检查对象是否是类的实例(但不是其子类的实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!