In this article, we will take a deep look into the getClass() Java method.
1. Where is the getClass() method located?
The getClass() method is located in the java.lang package and in Object.java class.
2. Is getClass() a native method?
Yes, getClass() is a native method in java.lang.Object class.
3. What is the return type of getClass() method?
The return type is Class (java.lang.Class).
4. Is getClass() method final?
Yes.
5. Does getClass take any parameters?
No.
6. Does getClass throw any exceptions?
No.
7. Syntax of getClass() method
public final native Class<?> getClass();
The getClass() method can be noted as a native method with a final and public access modifier. The return type of this method is of the Class.
8. What is getClass() method used for?
The java.lang package's Object class defines 11 standard methods, one of which is the getClass() method.
getClass method returns the runtime class of an Object in Java.
9. Changes over Java Versions
Open JDK Version | getClass method implimentation |
---|---|
Java 8 | No change in the method declaration since Java 1.0 to Java 8 |
Java 11 | method annotated with @HotSpotIntrinsicCandidate |
Java 17 | method annotated with @IntrinsicCandidate |
10. Usage of getClass method
- To determine the runtime class of an object in Java
- To determine the type of an runtime object.
- Using java.lang.Class to make use of reflection.
- Used in load classes into the Java Virtual Machine
To understand this method better, let us create an Employee class.
11. Examples
Example 1:
Employee.java
package org.example;
public class Employee {
private int employeeId;
private String employeeDateOfBirth;
private String employeeName;
private String employeeGender;
private String employeeDepartment;
public Employee(int empId, String empDateOfBirth, String empName, String empGender, String empDepartment) {
this.employeeId = empId;
this.employeeDateOfBirth = empDateOfBirth;
this.employeeName = empName;
this.employeeGender = empGender;
this.employeeDepartment = empDepartment;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeDateOfBirth() {
return employeeDateOfBirth;
}
public void setEmployeeDateOfBirth(String employeeDateOfBirth) {
this.employeeDateOfBirth = employeeDateOfBirth;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeGender() {
return employeeGender;
}
public void setEmployeeGender(String employeeGender) {
this.employeeGender = employeeGender;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
@Override
public String toString() {
return this.getClass() + " {" +
"employeeId=" + employeeId +
", employeeDateOfBirth='" + employeeDateOfBirth + '\'' +
", employeeName='" + employeeName + '\'' +
", employeeGender='" + employeeGender + '\'' +
", employeeDepartment='" + employeeDepartment + '\'' +
'}';
}
}
package org.example;
public class Employee {
private int employeeId;
private String employeeDateOfBirth;
private String employeeName;
private String employeeGender;
private String employeeDepartment;
public Employee(int empId, String empDateOfBirth, String empName, String empGender, String empDepartment) {
this.employeeId = empId;
this.employeeDateOfBirth = empDateOfBirth;
this.employeeName = empName;
this.employeeGender = empGender;
this.employeeDepartment = empDepartment;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeDateOfBirth() {
return employeeDateOfBirth;
}
public void setEmployeeDateOfBirth(String employeeDateOfBirth) {
this.employeeDateOfBirth = employeeDateOfBirth;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeGender() {
return employeeGender;
}
public void setEmployeeGender(String employeeGender) {
this.employeeGender = employeeGender;
}
public String getEmployeeDepartment() {
return employeeDepartment;
}
public void setEmployeeDepartment(String employeeDepartment) {
this.employeeDepartment = employeeDepartment;
}
@Override
public String toString() {
return this.getClass() + " {" +
"employeeId=" + employeeId +
", employeeDateOfBirth='" + employeeDateOfBirth + '\'' +
", employeeName='" + employeeName + '\'' +
", employeeGender='" + employeeGender + '\'' +
", employeeDepartment='" + employeeDepartment + '\'' +
'}';
}
}
As you may see in the toString() method I have used this.getClass() instead of hard-coding the class name.
EmpClient.javapackage org.example;
public class EmpClient {
public static void main(String[] args) {
Employee employeeSam = new Employee(1,"1990-02-13","male","Sam","IT");
System.out.println(employeeSam.toString());
}
}
Output:
class org.example.Employee
{employeeId=1, employeeDateOfBirth='1990-02-13', employeeName='male', employeeGender='Sam', employeeDepartment='IT'}
As you can see the getClass() method will return the class name of the current runtime object
Note: The Class object returned is the object that is locked by the static synchronized methods of the represented class.
Example 2:
String name = "Sam";
System.out.println(name.getClass());
Output:
class java.lang.String
Example 3:
List list1 = new ArrayList();
list1.add("Sam");
System.out.println(list1.getClass());
System.out.println(list1.get(0).getClass());
Output:
class java.util.ArrayList
class java.lang.String
Example 4:
Object myObject = new Object();
System.out.println(myObject.getClass());
Output:
class java.lang.Object
Example 5:
Class whatClass = "Sam".getClass();
System.out.println(whatClass);
Output:
class java.lang.String
Example 6:
package org.example;
public class EnumExample {
enum E { JAN,FEB,MAR,APR}
public static void main(String[] args) {
System.out.println(E.JAN.getClass());
}
}
Output:
class org.example.EnumExample$E
12. getClass alternative for primitives
You will get comiplation error when you try to make use of getClass method with primitives.
Compilation Error:int myInt = 20;
Class whatClass = myInt.getClass() //Compilation Error
Make use of the .class syntax to return the Class corresponding to primitives.
int myInt = 20;
Class myClass = int.class;
System.out.println(myClass);
Output:
int
13. Where is getClass used in Java core library
You do not need to look for the usage of getClass in any other class, you can find its usage with the Object class itself. Take a look at the toString() method implementation.
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
14. Reflection example with getClass
public static void main(String[] args) {
Employee employee = new Employee(1,"1995-01-01","Mike","Male","Finance");
Class empClass = employee.getClass();
Method[] methods = empClass.getMethods();
for(Method method: methods)
System.out.println(method.getName());
}
Output:
toString
getEmployeeId
setEmployeeId
getEmployeeDateOfBirth
setEmployeeDateOfBirth
getEmployeeName
setEmployeeName
getEmployeeGender
setEmployeeGender
getEmployeeDepartment
setEmployeeDepartment
wait
wait
wait
equals
hashCode
getClass
notify
notifyAll
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- [Solution] fatal: not a git repository (or any of the parent directories): .git - Git
- Java Multi-line String Example - Java
- Fetch only content-type using cURL Command - cURL
- How to display hidden files in Eclipse (dot prefixed files) - Eclipse
- How to Launch Terminal App in Mac - MacOS
- Emulator: Warning: restoring GLES1 context from snapshot. App may need reloading. - Android-Studio
- How to force re-download Gradle Dependencies - Gradle
- How to check the size of a Docker Container - Docker