How do I determine the class name of an object?
Author: Deron Eriksson
Description: This Java tutorial describes how to determine the class name of an object.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 1.5.4


If you have a JavaSW 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, you can call getName() on the class. This is illustrated in the ClassNameTest class below.

ClassNameTest.java

package test;

import java.io.IOException;
import java.util.HashMap;

public class ClassNameTest {

	public static void main(String args[]) throws IOException {
		Object o = "hello";
		System.out.println("class name is: " + o.getClass().getName());
		o = new HashMap();
		System.out.println("class name is: " + o.getClass().getName());
		Boolean b = new Boolean(true);
		o = b;
		System.out.println("class name is: " + o.getClass().getName());
		o = new StringBuffer();
		Class c = o.getClass();
		System.out.println("class name is: " + c.getName());
	}
}

Executing the ClassNameTest class produces the following console output:

class name is: java.lang.String
class name is: java.util.HashMap
class name is: java.lang.Boolean
class name is: java.lang.StringBuffer

For the nuances related to displaying the name of array objects, you can consult the Javadoc API documentation pertaining to the getName() method of Class.