Java - is there a “subclassof” like instanceof?

£可爱£侵袭症+ 提交于 2019-12-03 22:18:43

instanceof can handle that just fine.

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.

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.

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:

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.

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
}

You might want to look at someObject.getClass().isAssignableFrom(otherObject.getClass());

Fazal

There is no direct method in Java to check subclass. instanceof Event would return back true for any sub class objects

The you could do getClass() on the object and then use getSuperclass() method on Class object to check if superclass is Event.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!