This post will discuss how to determine the class name of the underlying class of objects in Java.

1. Class’s get*Name() methods

The simplest way is to call the getClass() method that returns the class’s name 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 a recent addition to JDK in Java SE 8 which internally calls getClass().

⮚ For class objects:

⮚ For Reference Types:

⮚ For Arrays:

2. Using Class.getEnclosingClass() method

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

 
We can also define an inner class to get the 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 the current method’s stack frame (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. We can find the current method’s stack frame (containing class information) 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.

That’s all about checking class names in Java.