views:

3213

answers:

5

If class B and class C extend class A and I have an object of type B or C, how can I determine which it instantiates?

+6  A: 

Use Object.getClass(). It returns the runtime type of the object.

Bill the Lizard
+17  A: 
if (obj instanceof C) {
//your code
}
01
A: 

You can use:

Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object

HTH. But I think most of the time it is no good practice to use that for control flow or something similar...

Johannes Weiß
+9  A: 

Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.

If your design is good, you should not find yourself needing to use getClass() or instanceof.

Any of the suggested methods will do, but just something to keep in mind, design-wise.

Yuval A
Yeah, probably 99% of the uses of getClass and instanceof can be avoided with polymorphic method calls.
Bill the Lizard
i am in agreement.in this case i'm working with objects generated from xml following a poorly designed schema which i do not have ownership of.
carrier
That's generally the case in these situations, legacy code, bad design not in your ownership, etc...
Yuval A
Not nessecarily. Sometimes separation of interfaces is good. There are times when you want to know if A is a B, but you don't want to make it mandatory that A is a B, as only A is required for most functionality - B has optional functionality.
MetroidFan2002
A: 

there is also a .isInstance method on the "Class" class. if you get an objects class via myBanana.getClass() you can see if your object myApple is an instance of the same class as myBanana via

myBanana.getClass().isInstance(myApple)

Andreas Petersson