Im overriding an equals() method and I need to know if the objec开发者_如何学JAVAt 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!
instanceof
can handle that just fine.
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());
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.
精彩评论