Java Object getClass() 方法



描述

Java Object getClass() 方法返回对象的运行时类。该 Class 对象是被表示类的静态同步方法锁定的对象。

声明

以下是java.lang.Object.getClass() 方法的声明

public final Class getClass()

参数

返回值

此方法返回表示对象运行时类的 Class 类型的对象。

异常

获取对象的类示例

以下示例演示了 java.lang.Object.getClass() 方法的用法。在这个程序中,我们创建了一个 GregorianCalendar 类的新的实例。现在使用 getClass() 方法,打印日历实例的类。

package com.tutorialspoint;

import java.util.GregorianCalendar;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a new GregorianCalendar object
      GregorianCalendar cal = new GregorianCalendar();

      // print current time
      System.out.println(cal.getTime());

      // print the class of cal
      System.out.println(cal.getClass());
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

Fri May 31 16:10:41 IST 2024
class java.util.GregorianCalendar

获取 Integer 对象的类示例

以下示例演示了 java.lang.Object.getClass() 方法的用法。在这个程序中,我们创建了一个 Integer 类的新的实例。现在使用 getClass() 方法,打印整数实例的类。

package com.tutorialspoint;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a new Integer
      Integer i = Integer.valueOf(5);

      // print i
      System.out.println(i);

      // print the class of i
      System.out.println(i.getClass());
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

5
class java.lang.Integer

获取 ArrayList 对象的类示例

以下示例演示了 java.lang.Object.getClass() 方法的用法。在这个程序中,我们创建了一个 ArrayList 类的新的实例。现在使用 getClass() 方法,打印 ArrayList 实例的类。

package com.tutorialspoint;

public class ObjectDemo {

   public static void main(String[] args) {

      // create a new Integer
      ArrayList<String> i = new ArrayList<>();

      // print i
      System.out.println(i);

      // print the class of i
      System.out.println(i.getClass());
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

[]
class java.util.ArrayList
java_lang_object.htm
广告
© . All rights reserved.