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
让我们看一个创建数组的程序Array.newInstance新实例使用Java反射-
import java.lang.reflect.Array; public class Example { public static void main(String[] args) { String[] arr = (String[]) Array.newInstance(String.class, 3); //创建一个新数组 Array.set(arr, 0, "A"); Array.set(arr, 1, "B"); Array.set(arr, 2, "C"); 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 = A Element 2 = B Element 3 = C