Determine Class name in Java

In this post, we will see how to determine class name of the underlying class of objects in Java.


 

1. Class’s get*Name() methods

The simplest way is to call getClass() method that returns the name of the class or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() which returns the simple name (as in source code) and canonical name of the underlying class respectively. getTypeName() is recent addition to JDK in Java SE 8 which internally calls getClass().

 

For class objects:

 

For Reference Types:

 

For Arrays:

 

2. Class.getEnclosingClass()

For anonymous inner class, we need to call Class.getEnclosingClass() that returns the immediately enclosing class of the underlying class.

 
We can also define a inner class to get class name of the enclosing class as shown below:

 

3. Using Stack Trace

We can get an array of stack trace elements representing the stack trace pertaining to a throwable. The first element of the returned array of stack trace contains stack frame of current method (which also stores class information).

 
The stack trace of a current thread also returns an array of stack trace elements representing the stack dump of this thread. The stack frame of current method (containing class information) can be found at index 1 of the array.

 
Please note that this method is not safe to use as few virtual machines may omit one or more stack frames from the stack trace under special circumstances.

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz