I've got a situation where I need to be able to dynamically discover the actual instantiated type of a Class.
For example, say I have the following classes:
Animal Dog extends Animal Cat extends Animal
I instantiate a Dog as follows: Animal dog = new Dog();
From within ANIMAL, I want to be able to tell what type of "Animal" object I have. It's very important to note here that in my actual example, I WILL NOT KNOW what subclass types are possible (so I can't code anything along the lines of if(Animal instanceof Dog), etc.
Every Object has a getClass() method that you can use to, um, get the class. See the link for other methods common to all Objects. In many cases, if you need behavior that depends on the class, it's better to put that behavior into the specific subclasses. But if you really need getClass(), the method is available for you. [ October 31, 2007: Message edited by: Jim Yingst ]
If you get into a situation where you find that you need runtime type information, be it using "instanceof" or using reflection or getClass(), it should raise a red flag that maybe the design of your code isn't really object oriented.
In most cases you can, and should, replace such a mechanism with polymorphism: create a common base class or interface and call the methods in concrete subclasses or implementations through the base class or interface.