检查对象是否是类的实例(但不是其子类的实例)
对于此示例:
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设计的目标是允许您以相同的方式处理任何 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.