Get Class Name in Java

In Java, just if you are given an object, you can tell the class name for which the object belongs; and also, its super classes etc. To get class name, the class you use is class Class. Do not confuse. There is a class called Class in Java like there exists Double class for data type double. This class Class you will come across in JDBC to load the driver as Class.forName().

The class Class is used extensively by Reflection.

The methods used are getClass (of Object class) and getName() (of class Class).
Following example uses these methods to get class name.
public class Test
{
  public static void main(String args[])
  {
    Test t1 = new Test();
 
    Class cls = t1.getClass();
 
    System.out.println("cls: " + cls);                      // prints class Test  
    System.out.println("cls.getName(): " + cls.getName());  // prints Test
  }
}

Get Class NameOutput Screenshot on Get Class Name in Java

For explanation, method signatures on the above code and for more objects refer Java get Class and get Name

Leave a Comment

Your email address will not be published.