java.lang.reflect.Array.newInstance() 方法示例



描述

java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) 方法建立一個具有指定元件型別和維數的新陣列。如果 componentType 表示非陣列類或介面,則新陣列具有 dimensions.length 個維度,並且 componentType 作為其元件型別。如果 componentType 表示陣列類,則新陣列的維度數等於 dimensions.length 和 componentType 的維度數之和。在這種情況下,新陣列的元件型別是 componentType 的元件型別。

宣告

以下是 java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) 方法的宣告。

public static Object newInstance(Class<?> componentType, int... dimensions)
   throws IllegalArgumentException, NegativeArraySizeException

引數

  • componentType − 表示新陣列的元件型別的 Class 物件。

  • dimensions − 一個 int 陣列,表示新陣列的維度。

返回值

新陣列。

異常

  • NullPointerException − 如果指定的 componentType 為 null。

  • IllegalArgumentException − 如果指定的 dimensions 引數是零維陣列,或者請求的維度數超過實現支援的陣列維度數的限制(通常為 255),或者 componentType 是 Void.TYPE。

  • ArrayIndexOutOfBoundsException − 如果指定的索引引數為負數。

示例

以下示例顯示了 java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) 方法的使用。

package com.tutorialspoint;

import java.lang.reflect.Array;

public class ArrayDemo {
   public static void main(String[] args) {

      String[][] stringArray = (String[][]) Array.newInstance(String.class, 3,3);

      Array.set(stringArray[0], 0, "Mahesh");
      Array.set(stringArray[1], 1, "Ramesh");
      Array.set(stringArray[2], 2, "Suresh");

      System.out.println("stringArray[0][0] = " + Array.get(stringArray[0], 0));
      System.out.println("stringArray[1][1] = " + Array.get(stringArray[1], 1));
      System.out.println("stringArray[2][2] = " + Array.get(stringArray[2], 2));
   }
}

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

stringArray[0][0] = Mahesh
stringArray[1][1] = Ramesh
stringArray[2][2] = Suresh
java_reflect_array.htm
廣告

© . All rights reserved.