java.lang.reflect.Array.newInstance(Class <?> componentType,int length)方法形成一个新数组,该数组具有参数中指定的组件类型和长度
声明-java.lang.reflect.Array.newInstance(Class <?> componentType,int length)方法声明如下-
public static Object newInstance(Class<?> componentType, int length) throws IllegalArgumentException, NegativeArraySizeException
让我们看一个程序,使用Java Reflection使用Array.newInstance创建一个整数数组-
import java.lang.reflect.Array; public class Example { public static void main(String[] args) { int[] arr = (int[]) Array.newInstance(int.class, 3); // creates a new array Array.set(arr, 0, 5); Array.set(arr, 1, 9); Array.set(arr, 2, 2); System.out.println("Element 1 = " + Array.get(arr, 0)); System.out.println("Element 2 = " + Array.get(arr, 1)); System.out.println("Element 3 = " + Array.get(arr, 2)); } }
输出结果
Element 1 = 5 Element 2 = 9 Element 3 = 2