Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an object's implemented class

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?

like image 416
Vivek Avatar asked Jan 27 '12 20:01

Vivek


People also ask

How do you print an object class?

Printing objects give us information about the objects we are working with. In C++, we can do this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class. In Java, we use toString() method. In Python, this can be achieved by using __repr__ or __str__ methods.

Can you print out an object in Java?

The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value.


2 Answers

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.

like image 57
NPE Avatar answered Oct 18 '22 02:10

NPE


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

like image 34
Robin Avatar answered Oct 18 '22 03:10

Robin