What is Java Object getClass() Method?
Java uses a method called getClass() provided by the class Object to get the class of any object used.Method Header
public final Class<?> getClass()
The method does not take any parameter and is called upon the object whose class needs to be fetched.
Return Type
This method returns the class of the “object”.Example
public class DriverClass {
public static void main(String[] args) {
Object myObject = 25;
Class myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = Float.NaN;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = Short.MIN_VALUE;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = 37.99999999000099990;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = Long.MAX_VALUE;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = "This is a String.";
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
}
}
Output
Class of "25" = java.lang.Integer
Class of "NaN" = java.lang.Float
Class of "-32768" = java.lang.Short
Class of "37.999999990001" = java.lang.Double
Class of "9223372036854775807" = java.lang.Long
Class of "This is a String." = java.lang.String
GO TO FULL VERSION