How to print an object's implemented class

25,894

Solution 1

I believe the interface name will be printed instead of the class that implemented this interface.

That's not correct: getClass().getName() will print the name of the class. The Javadoc is pretty clear on this:

public final Class<?> getClass()

Returns the runtime class of this Object.

Solution 2

With that statement you will print the runtime-class of that object, and not the interface. However, if you use a debugger there is no need for that System.out statement. You can just place a breakpoint and look at your variable in the debugger. The debugger will show you what the runtime class of your object is

Share:
25,894
Vivek
Author by

Vivek

"A learner in seek of answers to why and how questions. I will leave answers to what and when queries to one with great memory. It is now that I have realized about the depth of knowledge to successfully navigate the technology realm. Hence my solution to this realization is to learn by trying and not merely reading superficially. Hope to stick to my goal."

Updated on January 28, 2020

Comments

  • Vivek
    Vivek over 4 years

    During debugging without the aid of an IDE(Integrated Development Environment), I would like to determine an object's class. The catch is that the object is defined as an interface and I would like to determine the Object's class that is implementing this interface. So for instance I would like to print statements in the following setter method to print the implemented class name:

    public void setSomeObject(InterfaceType someObject) 
    {
       m_Object = someObject;
       System.out.println(someObject.getClass().getName());
    }
    

    I am in the process of testing this code sample and will provide more feedback on this question. As per docs of the java.lang.Class and java.lang.Object api, I believe the interface name will be printed instead of the class that implemented this interface.

    My question is how does one print the name of the implemented class instead of the interface in the above code sample?

  • Vivek
    Vivek over 12 years
    In this particular case, I am adding debug statements due to difficulties in running the code on an IDE. So please assume I do not have a debugger.
  • Robin
    Robin over 12 years
    Then just leave your statement as it is, as it will print the name of the class and not of the interface