Java Object getClass() Method

Java String类Java Object Class


The Object getClass() method is used to obtain the class of the runtime object of an object.

Syntax

object.getClass()

Parameters

  • None 。

Return Value

Returns the class of the object.

Example

The following example demonstrates the use of the getClass() method. String and ArrayList inherit from Object, so the getClass() method can be used directly:

Example

import java.util.ArrayList; class ExampleTest { public static void main(String[] args) { // getClass() with Object Object obj1 = new Object(); System.out.println("The class of obj1 is:" + obj1.getClass()); // getClass() with String String obj2 = new String(); System.out.println("The class of obj2 is:" + obj2.getClass()); // getClass() with ArrayList ArrayList<Integer> obj3 = new ArrayList<>(); System.out.println("The class of obj3 is:" + obj3.getClass()); } }

The output of the above program is:

obj1 的类为: class java.lang.Object
obj2 的类为: class java.lang.String
obj3 的类为: class java.util.ArrayList

Custom class calling the getClass() method:

Example

class ExampleTest { public static void main(String[] args) { //Create an object of the ExampleTest class ExampleTest obj = new ExampleTest(); //ExampleTest inherits the Object class, and Object is the superclass of all classes //Call the getClass() method System.out.println(obj.getClass()); } }

The output of the above program is:

class ExampleTest

Java String类Java Object Class

Other Extensions