Search code examples
javaoopprogramming-languages

Java - how to tell class of an object?


Given a method that accepts as a parameter a certain supertype. Is there any way, within that method, to determine the actual class of the object that was passed to it? I.e. if a subtype of the allowable parameter was actually passed, is there a way to find out which type it is? If this isn't possible can someone explain why not (from a language design perspective)? Thanks

Update: just to make sure I was clear

Context: MySubType extends MyType

void doSomething(MyType myType) {
  //determine if myType is MyType OR one of its subclasses
  //i.e. if MySubType is passed as a parameter, I know that it can be explicitly
  //cast to a MySubType, but how can I ascertain that its this type
  //considering that there could be many subclasses of MyType
}

Since the method signature specifies the parameter as being MyType, then how can one tell if the object is actually a subtype of MyType (and which one).


Solution

  • If you look at the javadoc for the Object class, you will find that every object supports getClass(). That's the Class of the object, and you can go from there.

    If the object is MyType then getClass() == MyType.class'. If the object is a superclass, thengetClass() != MyType.class`.

    There are only these possibilities. If the type of the param is MyType, and MyType is a class and not an interface, then either the object is MyClass or it's a subtype. If it's a subtype, then getClass() is returning the Class for the subtype. You can use the API of Class to explore it.

    You can, of course, use reflection to explore the type hierarchy. You can ask MyType.class for a list of its direct subclasses, and recurse from there, and have a fine old time. But you don't need to.