Java - 是否有像 instanceof 这样的“subclassof”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2699788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - is there a "subclassof" like instanceof?
提问by msr
Im overriding an equals() method and I need to know if the object is an instance of a Event's subclass (Event is the superclass). I want something like "obj subclassof Event". How can this be made?
我覆盖了一个 equals() 方法,我需要知道对象是否是 Event 子类的实例(Event 是超类)。我想要类似“obj subclassof Event”的东西。这怎么可能?
Thanks in advance!
提前致谢!
采纳答案by Ken Bloom
instanceof
can handle that just fine.
instanceof
可以处理得很好。
回答by DaveJohnston
If obj is a subclass of Event then it is an instanceof. obj is an instanceof every class/interface that it derives from. So at the very least all objects are instances of Object.
如果 obj 是 Event 的子类,那么它就是一个 instanceof。obj 是它派生自的每个类/接口的实例。所以至少所有的对象都是 Object 的实例。
回答by Fazal
There is no direct method in Java to check subclass.
instanceof Event
would return back true for any sub class objects
Java 中没有直接的方法来检查子类。
instanceof Event
将为任何子类对象返回 true
The you could do getClass()
on the object and then use getSuperclass()
method on Class
object to check if superclass is Event
.
你可以getClass()
在对象上做,然后getSuperclass()
在Class
对象上使用方法来检查超类是否是Event
.
回答by z5h
You might want to look at someObject.getClass().isAssignableFrom(otherObject.getClass());
你可能想看看 someObject.getClass().isAssignableFrom(otherObject.getClass());
回答by Adrian
With the following code you can check if an object is a class that extends Event but isn't an Event class instance itself.
使用以下代码,您可以检查对象是否是扩展 Event 但不是 Event 类实例本身的类。
if(myObject instanceof Event && myObject.getClass() != Event.class) {
// then I'm an instance of a subclass of Event, but not Event itself
}
By default instanceof
checks if an object is of the class specified or a subclass (extends or implements) at any level of Event.
默认情况下,instanceof
在任何级别的 Event 中检查对象是否属于指定的类或子类(扩展或实现)。
回答by Kevin Brock
Really instanceof
ought to be good enough but if you want to be sure the class is really a sub-class then you could provide the check this way:
真的instanceof
应该足够好,但是如果您想确保该类确实是一个子类,那么您可以通过以下方式提供检查:
if (object instanceof Event && object.getClass() != Event.class) {
// is a sub-class only
}
Since Adrian was a little ahead of me, I will also add a way you could do this with a general-purpose method.
由于 Adrian 有点领先于我,我还将添加一种您可以使用通用方法执行此操作的方法。
public static boolean isSubClassOnly(Class clazz, Object o) {
return o != null && clazz.isAssignableFrom(o) && o.getClass() != clazz;
}
Use this by:
通过以下方式使用:
if (isSubClassOnly(Event.class, object)) {
// Sub-class only
}