
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Class from an Object in Java
The runtime class of an object can be obtained using the java.lang.Object.getClass(). Also, the getName() method is used to get the name of the class.
A program that demonstrates getting the class of an object using the getClass() method is given as follows −
Example
public class Demo { public static void main (String [] args) { Integer integer = new Integer(10); Class c = integer.getClass(); System.out.println ("The class is: " + c.getName()); c = new Demo().getClass(); System.out.println ("The class is: " + c.getName()); } }
Output
The class is: java.lang.Integer The class is: Demo
Now let us understand the above program.
First a new Integer is created. Then the getClass() method is used to obtain the runtime class. Finally the getName() method is used to get the name of the class i.e. java.lang.Integer and print it. A code snippet which demonstrates this is as follows −
Integer integer = new Integer(10); Class c = integer.getClass(); System.out.println ("The class is: " + c.getName());
After this, the getClass() method is used to obtain the runtime class of an object of Demo. Then the getName() method is used to get the name of the class i.e. Demo and print it. A code snippet which demonstrates this is as follows −
c = new Demo().getClass(); System.out.println ("The class is: " + c.getName());