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?
Thanks in advance!
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?
Thanks in advance!
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());
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.