Ako určiť triedu objektu?

Ak triedy B a C rozširujú triedu A a mám objekt typu B alebo C, ako môžem určiť, ktorého typu je inštanciou?

Riešenie
if (obj instanceof C) {
//your code
}
Komentáre (6)

Použite Object.getClass(). Vráti runtime typ objektu.

Komentáre (3)

Môžete použiť:

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

HTH. Ale myslím si, že väčšinou nie je dobré používať to pre control flow alebo niečo podobné...

Komentáre (1)