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.