In Java, the user’s data is stored in various primitive data types, objects, lists, arrays, or maps. With an enormous line of codes, it becomes a headache to identify which type of data is being stored. To overcome this issue, Java provides a “getClass()” method. This method is available for the “Object” class, “Class” class, and “Writer” Class. However, the implementation procedure of a “getClass()” method remains the same among all classes.
This guide covers the mentioned section to describe the “Object getClass()” method in Java:
- How to Use the Java Object getClass() Method?
- Bonus Tip: Use of getClass() Method With the Writer Class
- Conclusion
How to Use the Java Object getClass() Method?
The “getClass()” method of an Object class is provided by the “java.lang” package. The main purpose of this method is to return the runtime class of the provided object or provide the library in which that class or data type exists. To be more clear, it returns the corresponding class as a library.
Syntax
The syntax of declaring the Object “getClass()” method in Java is:
public final Class<?> getClass()
The syntax for calling the mentioned method is:
targetObj.getClass();
Take a look at the below-mentioned examples to understand the Object getClass() method in Java.
Example 1: Use of getClass() Method on Object Class in Java
In this example, multiple data type values are assigned as the value for the created Object class. The “getClass()” and “getName()” methods are then assigned over the created class instance to retrieve the object class name:
import java.util.*;
public class javabeat {
public static void main(String[] args) {
Object targetObj = 0;
Class demoObjClass = targetObj.getClass();
System.out.println("\nThe provided Object Containing \'" + targetObj + "\' Value has the Class of: \n\t" + demoObjClass.getName());
targetObj = Float.NaN;
demoObjClass = targetObj.getClass();
System.out.println("\nThe provided Object Containing \'" + targetObj + "\' Value has the Class of: \n\t" + demoObjClass.getName());
targetObj = "This is a JavaBeat Article.";
demoObjClass = targetObj.getClass();
System.out.println("\nThe provided Object Containing \'" + targetObj + "\' Value has the Class of: \n\t" + demoObjClass.getName())
targetObj = Short.MIN_VALUE;
demoObjClass = targetObj.getClass();
System.out.println("\nThe provided Object Containing \'" + targetObj + "\' Value has the Class : \n\t" + demoObjClass.getName());
targetObj = 21.96677788890005543336660;
demoObjClass = targetObj.getClass();
System.out.println("\nThe provided Object Containing \'" + targetObj + "\' Value has the Class of: \n\t" + demoObjClass.getName());
targetObj = Long.MAX_VALUE;
demoObjClass = targetObj.getClass();
System.out.println("\nThe provided Object Containing \'" + targetObj + "\' Value has the Class of: \n\t" + demoObjClass.getName());
}
}
The explanation of the above code is as follows:
- First, import the required “java utilities” using the “import” keyword. Create a class “javabeat” that contains a “main()” method init.
- Next, create an “Object” type variable “targetObj” and assign it a random integer type value.
- Now, apply the “getClass()” method on the “targetObj” to retrieve its runtime class. Store this retrieved result in the “class” type variable named “demoObjClass”.
- Then, apply the “getName()” method on “demoObjClass” to display the retrieved runtime class and display the result on the console.
- Repeat the same process by assigning the different types of values to the “targetObj” variable.
- Also, apply the “getClass()” and “getName()” methods to retrieve the runtime class of the assigned object value type.
The generated output shows the targeted values and their retrieved runtime classes:
Example 2: Use of getClass() Method to Explore Runtime Classes for Objects
In this example, the “getClass()” method is used to retrieve, runtime classes of the “Class” type variable, “AraryList” and “LinkedList” classes, and Java runtime exception:
In the above code block:
- First, the class named “javabeat” is created and inside this class, the “main()” method is defined.
- Next, define a String type variable “str” and assign it a dummy value. Also, declare an object of “Class” named “demoVar” which can hold only String-type values.
- Apply the “getClass()” method on “str” and store the result in the “demoVar” object which is then displayed on the console.
- Then, create a new object of “ArrayList” and “linkedList” namely “arrayListObj” and “linkedListObj”.
- After that, apply the “getClass()” method on both created objects to retrieve their runtime classes from where they belong. The returned result is also printed on the console for verification purposes.
- Finally, declare a new instance “exceptionVar” of “runtimeException” using the “new” keyword. In addition, apply the “getClass()” method on the created instance and store the returned result showing the runtime class on the console.
The generated output shows that runtime classes for provided objects have been retrieved using the “getClass()” method:
Example 3: Use of the getClass() Method With Queue Implementations
In this case, the “getClass()” method is used to retrieve the runtime class of a provided queue type. The queue is passed from the “main()” method to the custom-defined function. The code for the mentioned scenario is stated below:
import java.util.*;
public class javabeat{
static void queueImplement(Queue providedQueue) {
Class classObj = providedQueue.getClass();
System.out.println("The runtime class for Provided Queue is: " + classObj);
}
public static void main(String[] args) {
PriorityQueue<Integer> priorityObj = new PriorityQueue<Integer>();
ArrayDeque<Integer> arrayObj = new ArrayDeque<Integer>();
queueImplement(priorityObj);
queueImplement(arrayObj);
}
}
In the above code snippet:
- First, the class named “javabeat” is created. Inside it, a custom method named “queueImplement()” is created that accepts a single parameter having the type of “Queue”.
- Inside the created method, apply the “getClass()” method on the received parameter. Store the retrieved result in the “Class” object named “classObj” and display it on the console.
- Next, define the “main()” method and create new instances for “PriorityQueue” and “ArrayDeque”. Assign the newly created instances names of “priorityObj” and “arrayObj” respectively.
- Finally, pass both instances as an argument for “priorityObj” and “arrayObj”.
The output shows the retrieved runtime classes for both provided queues:
Bonus Tip: Use of getClass() Method With the Writer Class
As already discussed, the Writer class also provides the “getClass()” method to perform the same functionality of retrieving the runtime classes. For instance, runtime classes for the “OutputStreamWriter” and “PrintWriter” classes are retrieved in the below-mentioned code snippet:
import java.io.*;
class javabeat{
public static void main(String[] args) {
try {
Writer outObj = new OutputStreamWriter(System.out);
Writer printObj = new PrintWriter(System.out);
System.out.println("\nRuntime Parent Class of OutputStreamWriter class is: \n" + outObj.getClass());
System.out.println("\nRuntime Parent Class of PrintWriter class is: \n" + printObj.getClass());
}
catch (Exception excep) {
System.out.println(excep);
}
}
}
The above code works like this:
- First, import the “java.io.*” package and create a class named as “javabeat”.
- Next, define a “main()” method containing the “try/catch” block. In the “try” section, create instances named “outObj” and “printObj” for the “OutputStreamWriter” and “PrintWriter” classes.
- Then, apply the “getClass()” method on both created instances to retrieve their runtime parent class.
- Finally, using the “System.out.println()” method displays the retrieved results on the console.
- Also, pass the “Exception” as an argument in the “catch” block to select and display any occurred exception during the process.
The output shows the working of a getClass() method with the Writer Class:
That’s all about the working of an Object getClass() method in Java.
Conclusion
The “getClass()” method of the Object class retrieves the root class of the targeted object at runtime. This method can also be used with the “Class” or “Writer” classes. It is a part of the reflection mechanism that allows users to inspect and manipulate classes, methods, fields, and other elements of the Java program at runtime. This guide has explained the working of the object getClass() method in Java.