Hello,
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!
Hello,
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!
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.
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
.
You might want to look at someObject.getClass().isAssignableFrom(otherObject.getClass());
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
}
Let your IDE (Eclipse, NetBeans, IntelliJ IDEA) generate the equals(..)
method for you. It should be somewhere on right click > source