- java.lang.reflect Package Classes
- java.lang.reflect - Home
- java.lang.reflect - AccessibleObject
- java.lang.reflect - Array
- java.lang.reflect - Constructor<T>
- java.lang.reflect - Field
- java.lang.reflect - Method
- java.lang.reflect - Modifier
- java.lang.reflect - Proxy
- java.lang.reflect Package Extras
- java.lang.reflect - Interfaces
- java.lang.reflect - Exceptions
- java.lang.reflect - Error
- java.lang.reflect Useful Resources
- java.lang.reflect - Quick Guide
- java.lang.reflect - Useful Resources
- java.lang.reflect - Discussion
java.lang.reflect.Array.newInstance() Method Example
Description
The java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method creates a new array with the specified component type and dimensions. If componentType represents a non-array class or interface, the new array has dimensions.length dimensions and componentType as its component type. If componentType represents an array class, the number of dimensions of the new array is equal to the sum of dimensions.length and the number of dimensions of componentType. In this case, the component type of the new array is the component type of componentType.
Declaration
Following is the declaration for java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method.
public static Object newInstance(Class<?> componentType, int... dimensions) throws IllegalArgumentException, NegativeArraySizeException
Parameters
componentType − the Class object representing the component type of the new array.
dimensions − an array of int representing the dimensions of the new array.
Return Value
the new array.
Exceptions
NullPointerException − If the specified componentType is null.
IllegalArgumentException − if the specified dimensions argument is a zero-dimensional array, or if the number of requested dimensions exceeds the limit on the number of array dimensions supported by the implementation (typically 255), or if componentType is Void.TYPE.
ArrayIndexOutOfBoundsException − If the specified index argument is negative.
Example
The following example shows the usage of java.lang.reflect.Array.newInstance(Class<?> componentType, int... dimensions) method.
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)); } }
Let us compile and run the above program, this will produce the following result −
stringArray[0][0] = Mahesh stringArray[1][1] = Ramesh stringArray[2][2] = Suresh