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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With