问题
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!
回答1:
instanceof
can handle that just fine.
回答2:
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.
回答3:
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
}
回答4:
You might want to look at someObject.getClass().isAssignableFrom(otherObject.getClass());
回答5:
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
.
回答6:
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.
来源:https://stackoverflow.com/questions/2699788/java-is-there-a-subclassof-like-instanceof