Java Class isPrimitive() 方法



描述

Java Class isPrimitive() 方法用於確定指定的 Class 物件是否表示一個原始型別。有九個預定義的 Class 物件來表示八種原始型別和 void。這些是由 Java 虛擬機器建立的,並且具有與它們表示的原始型別相同的名稱,即 boolean、byte、char、short、int、long、float 和 double。

宣告

以下是 java.lang.Class.isPrimitive() 方法的宣告

public boolean isPrimitive()

引數

返回值

當且僅當此類表示原始型別時,此方法返回 true。

異常

獲取非原始類的原始狀態示例

以下示例演示了 java.lang.Class.isPrimitive() 方法的使用。在這個程式中,我們建立了一個 ClassDemo 的例項,然後使用 getClass() 方法檢索該例項的類。使用 isPrimitive(),我們檢索了類的原始類狀態,並列印結果。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      // returns the Class object associated with this class
      ClassDemo cl = new ClassDemo();
      Class c1Class = cl.getClass();

      // checking for primitive type
      boolean retval1 = c1Class.isPrimitive();
      System.out.println("c1 is primitive type? = " + retval1);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

c1 is primitive type? = false

獲取原始類的原始狀態示例

以下示例演示了 java.lang.Class.isMemberClass() 方法的使用。在這個程式中,我們使用了 int 的類,然後使用 isPrimitive() 檢索類的原始類狀態,並列印結果。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      // returns the Class object associated with an integer
      int k = 5;
      Class kClass = int.class;

      // checking for primitive type?
      boolean retval2 = kClass.isPrimitive();
      System.out.println("k is primitive type? = " + retval2);
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

k is primitive type? = true
java_lang_class.htm
廣告