Java Class getComponentType() 方法



描述

Java Class getComponentType() 方法返回表示陣列元件型別的 Class。如果此類不表示陣列類,則此方法返回 null。

宣告

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

public Class<?> getComponentType()

引數

返回值

如果此類是陣列,則此方法返回表示此類元件型別的 Class。

異常

獲取字串陣列的元件型別示例

以下示例演示了 java.lang.Class.getComponentType() 方法的用法。在這個程式中,我們建立了一個字串陣列的例項,然後使用 getClass() 方法檢索例項的類。使用 getComponentType(),我們檢索了類的元件型別,並將結果打印出來。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      String[] arr = new String[] {"admin"};

      // returns the Class representing the component type
      Class arrClass = arr.getClass();
      Class componentType = arrClass.getComponentType();
      if (componentType != null) {
         System.out.println("ComponentType = " + componentType.getName());
      } else {
         System.out.println("ComponentType is null");
      }
   }
} 

輸出

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

ComponentType = java.lang.String

獲取 List 類的元件型別示例

以下示例演示了 java.lang.Class.getComponentType() 方法的用法。在這個程式中,檢索了 List 類的類。使用 getComponentType(),我們檢索了類的元件型別,並將結果打印出來。

package com.tutorialspoint;

import java.util.List;

public class ClassDemo {

   public static void main(String[] args) {

      // returns the Class representing the component type
      Class arrClass = List.class;
      Class componentType = arrClass.getComponentType();
      if (componentType != null) {
         System.out.println("ComponentType = " + componentType.getName());
      } else {
         System.out.println("ComponentType is null");
      }
   }
} 

輸出

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

ComponentType is null

獲取 Integer 類的元件型別示例

以下示例演示了 java.lang.Class.getComponentType() 方法的用法。在這個程式中,檢索了 Integer 類的類。使用 getComponentType(),我們檢索了類的元件型別,並將結果打印出來。

package com.tutorialspoint;

public class ClassDemo {

   public static void main(String[] args) {

      // returns the Class representing the component type
      Class arrClass = Integer.class;
      Class componentType = arrClass.getComponentType();
      if (componentType != null) {
         System.out.println("ComponentType = " + componentType.getName());
      } else {
         System.out.println("ComponentType is null");
      }
   }
} 

輸出

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

ComponentType is null
java_lang_class.htm
廣告
© . All rights reserved.