11

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?

5
  • what is the question? what will it print?
    – amit
    Jan 27, 2012 at 20:40
  • 3
    Why wouldn't you just run it and find out before writing this post? As is, there's really no question... Jan 27, 2012 at 20:40
  • 1
    This isn't a question. And it will print the name of the class.
    – smparkes
    Jan 27, 2012 at 20:40
  • My question is how does one print the name of the implemented class instead of the interface in the above code sample?
    – Vivek
    Jan 27, 2012 at 20:49
  • This is why you try things first (and read javadoc). Jan 27, 2012 at 21:14

2 Answers 2

23

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.

1

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

2
  • 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.
    – Vivek
    Jan 27, 2012 at 20:54
  • Then just leave your statement as it is, as it will print the name of the class and not of the interface
    – Robin
    Jan 27, 2012 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.