在 Java 中獲取陣列物件的元件型別


要獲取 Java 中陣列物件的元件型別,我們使用 getComponentType() 方法。getComponentType() 方法返回表示陣列元件型別的類。如果該類不是陣列類,則此方法返回 null。

宣告 − java.lang.Class.getComponentType() 方法宣告如下 -

public Class<?> getComponentType()

讓我們看看一個在 Java 中獲取陣列物件的元件型別的程式 -

示例

 線上演示

public class Example {
   public static void main(String[] args) {
      int[] array = new int[] {1,2,3};
      // obtain the Class of the component type
      Class arrayClass = array.getClass();
      // obtaining the component type
      Class component = arrayClass.getComponentType();
      if (component != null) {
         System.out.println("Component type is " + component.getName());
      } else {
         System.out.println("Component type is null");
      }
   }
}

輸出

Component type is int

更新於: 25-6 月-2020

2K+ 瀏覽

開啟您的職業生涯

完成課程並獲得認證

開始
廣告