- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create array with Array.newInstance with Java Reflection
The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method forms a new array with the component type and length as specified in the arguments
Declaration − The java.lang.reflect.Array.newInstance(Class<?> componentType, int length) method is declared as follows −
public static Object newInstance(Class<?> componentType, int length) throws IllegalArgumentException, NegativeArraySizeException
Let us see a program to create array with Array.newInstance with Java Reflection −
Example
import java.lang.reflect.Array; public class Example { public static void main(String[] args) { String[] arr = (String[]) Array.newInstance(String.class, 3); // creates a new array 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)); } }
Output
Element 1 = A Element 2 = B Element 3 = C
Advertisements