How determine the class name of an object

If you have a Java object, you can obtain it’s class object by calling getClass() on the object. To determine a String representation of the name of the class,we can call getName() on the class. sample ClassNameExample class below.

import java.util.ArrayList;
import java.util.HashMap;

public class ClassNameExample {

    public static void main(String args[])  {
        
        Object o = "Hello World";
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o = new HashMap();
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o = new Boolean(true);
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o = new StringBuffer();
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o=new ArrayList(); 
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o=new Exception(); 
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o=new ClassNameExample();
        
        System.out.println("ClassName is: " + o.getClass().getName());
        
        o=new Thread();
        System.out.println("ClassName is: " + o.getClass().getName());
        
    }
}

 

Output:

ClassName is: java.lang.String
ClassName is: java.util.HashMap
ClassName is: java.lang.Boolean
ClassName is: java.lang.StringBuffer
ClassName is: java.util.ArrayList
ClassName is: java.lang.Exception
ClassName is: test.ClassNameExample
ClassName is: java.lang.Thread
Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s