检查,如果对象是类的一个实例(但一个子类的不是一个实例) [英] Check if a object is a instance of a class (but not a instance of a subclass)
问题描述
在这个例子中:
public class Foo{}
public class Bar extends Foo{}
....
void myMethod(Foo qux){
if (checkInstance(qux,Foo.class)){
....
}
}
我怎么能检查是否 qux 如果富的一个实例(但FOO的子类,而不是一个实例)?那就是:
how can I check if qux if a instance of Foo (but not a instance of a subclass of foo)? That is:
- checkInstance(qux,让Foo.class)=真
- checkInstance(qux,Bar.class)= FALSE
有一些语句例如的instanceof 此检查?我应该使用 qux.getClass()。等于(让Foo.class)
Is there some kind of statement like instanceof for this check? of I should use qux.getClass().equals(Foo.class)
推荐答案
如果你要做到这一点,唯一的办法是在的getClass()。等于(让Foo.class)
选择您所建议的。
If you have to do this, the only way would be the getClass().equals(Foo.class)
option you've suggested.
然而,面向对象的设计的目的是让你来治疗的任意的富
以相同的方式。无论是否实例是一个子类,应该是不相关的一个正常的程序。
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屋!