Home » Core Java » class » Get an object’s class name

About Ilias Tsagklis

Avatar photo
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

Get an object’s class name

With this example we are going to demonstrate how to get an object’s class name. We
can get the class name for any object as shown in the steps below:

  • We create a new Class object.
  • We set the Class object to String.class and get its name using getName() API method of Class.
  • We follow the same steps for other objects, such as java.awt.geom.Ellipse2D, int, int[], String[] and Void.Type.

Let’s take a look at the code snippet that follows:  
  

package com.javacodegeeks.snippets.core;

import java.awt.geom.Ellipse2D;

public class GetAnObjectClassName {
	
	public static void main(String[] args) {
		
		Class<?> clazz = null;
		
		clazz = String.class;
		System.out.println("String: " + clazz.getName());
		
		clazz = Ellipse2D.Double.class;
		System.out.println("Ellipse2D.Double: " + clazz.getName());
		
		clazz = int.class;
		System.out.println("int: " + clazz.getName());
		
		clazz = int[].class;
		System.out.println("int[]: " + clazz.getName());
		
		clazz = String[].class;
		System.out.println("String[]: " + clazz.getName());
		
		clazz = Void.TYPE;
		System.out.println("Void.TYPE: " + clazz.getName());
		
	}

}

Output:

String: java.lang.String
Ellipse2D.Double: java.awt.geom.Ellipse2D$Double
int: int
int[]: [I
String[]: [Ljava.lang.String;
Void.TYPE: void

  
This was an example of how to get an object’s class name in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments