- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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());
- Related Articles
- Get super class of an object in Java
- How to create an object from class in Java?
- Object class in Java
- Get all declared fields from a class in Java
- Get a value from Unit Tuple class in Java
- Get a value from Pair Tuple class in Java
- Can we create an object of an abstract class in Java?
- Object and class in Java
- Object class in java programming
- Can we throw an object of generic class in java?
- Can we create an object for the abstract class in java?
- How to get a stream from Optional class in Java 9?
- Method of Object class in Java
- Get the Component Type of an Array Object in Java
- How to prevent object of a class from garbage collection in Java?
