views:

310

answers:

7

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!

+13  A: 

instanceof can handle that just fine.

Ken Bloom
Yep, `if (mysubclass instanceof Event) //go nuts..`
Paolo
Good thing you even don't have to check for `null`
Alexander Pogrebnyak
A: 

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.

DaveJohnston
+1  A: 

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.

Fazal
A: 

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

z5h
That's only useful if you have only class information. But in the `equals()` you have the both **instances** to your availability.
BalusC
Yes, you're right. I used the word 'might' for a reason. e.g. Writing a reusable "equalsHelper" method that does some preliminary checks for you. The correct information had already been posted so I just wanted to add some other consideration.
z5h
+10  A: 
Adrian
Guess we had the same idea but you got here first.
Kevin Brock
Why thank you sir :-)The other way to do it is to make Event abstract, or an interface, and not bother checking that your object is specifically an instance of it, because it can't be.
Adrian
+3  A: 

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
}
Kevin Brock
Paggas
@Paggas: I would consider that a programming error and thus want to have the NullPointerException. Basically it's not possible to have `object instanceof null` so why allow `isSubClassOnly(null, object)`.
Kevin Brock
A: 

Let your IDE (Eclipse, NetBeans, IntelliJ IDEA) generate the equals(..) method for you. It should be somewhere on right click > source

Bozho