- 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 length) method creates a new array with the specified component type and length.
Declaration
Following is the declaration for java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method.
public static Object newInstance(Class<?> componentType, int length) throws IllegalArgumentException, NegativeArraySizeException
Parameters
componentType − the Class object representing the component type of the new array.
length − 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 length) 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); Array.set(stringArray, 0, "Mahesh"); Array.set(stringArray, 1, "Ramesh"); Array.set(stringArray, 2, "Suresh"); System.out.println("stringArray[0] = " + Array.get(stringArray, 0)); System.out.println("stringArray[1] = " + Array.get(stringArray, 1)); System.out.println("stringArray[2] = " + Array.get(stringArray, 2)); } }
Let us compile and run the above program, this will produce the following result −
stringArray[0] = Mahesh stringArray[1] = Ramesh stringArray[2] = Suresh
To Continue Learning Please Login
Login with Google