當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Class isPrimitive()用法及代碼示例

Class類isPrimitive()方法

  • isPrimitive() 方法可在java.lang包。
  • isPrimitive() 方法用於檢查此 Class 對象是否表示原始類型。
  • 在 Java 中,我們有一個預定義的 Class 對象來表示原始類型和 void,但重要的是 Class 對象具有與原始類型類似的名稱,例如 byte、char、short、int、long、float 和 double。
  • isPrimitive() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • isPrimitive() 方法在檢查原語時不拋出異常。

用法:

    public boolean isPrimitive();

參數:

  • 它不接受任何參數。

返回值:

這個方法的返回類型是boolean,它根據以下情況返回一個布爾值,

  • 當此 Class 對象表示原始類型時,它返回 true。
  • 當此 Class 對象不表示原始類型時,它返回 false。

例:

// Java program to demonstrate the example 
// of boolean isPrimitive() method of Class 

public class IsPrimitiveOfClass {
    public static void main(String[] args) {
        // Create and Return String class
        String str = new String();
        Class cl1 = str.getClass();

        // Create and Return short
        short sh = 10;
        Class cl2 = short.class;

        // We are checking the class denotes primitive type
        boolean b1 = cl1.isPrimitive();
        boolean b2 = cl2.isPrimitive();

        System.out.print("Is" + " " + cl1.getSimpleName() + " ");
        System.out.println("Primitive" + ":" + b1);

        System.out.print("Is" + " " + cl2.getSimpleName() + " ");
        System.out.println("Primitive" + ":" + b2);
    }
}

輸出

Is String Primitive:false
Is short Primitive:true


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java Class class isPrimitive() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。