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
2009-02-12 15:20:38
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ß
2009-02-12 15:22:57
+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
2009-02-12 15:25:53
Yeah, probably 99% of the uses of getClass and instanceof can be avoided with polymorphic method calls.
Bill the Lizard
2009-02-12 15:28:17
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
2009-02-12 15:32:31
That's generally the case in these situations, legacy code, bad design not in your ownership, etc...
Yuval A
2009-02-12 15:37:40
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
2009-02-12 20:33:38
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
2009-02-12 16:04:32