- 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 new instance of an Array with Java Reflection Method
A new instance of an Array can be created using the java.lang.reflect.Array.newInstance() method. This method basically creates a new array with the required component type as well as length.
A program that demonstrates the creation of an array using the Array.newInstance() method is given as follows −
Example
import java.lang.reflect.Array; public class Demo { public static void main (String args[]) { int arr[] = (int[])Array.newInstance(int.class, 5); Array.set(arr, 0, 5); Array.set(arr, 1, 1); Array.set(arr, 2, 9); Array.set(arr, 3, 3); Array.set(arr, 4, 7); System.out.print("The array elements are: "); for(int i: arr) { System.out.print(i + " "); } } }
Output
The array elements are: 5 1 9 3 7
Now let us understand the above program.
A new array instance is created using the Array.newInstance() method. Then the Array.set() method is used to set the values for the array. A code snippet which demonstrates this is as follows −
int arr[] = (int[])Array.newInstance(int.class, 5); Array.set(arr, 0, 5); Array.set(arr, 1, 1); Array.set(arr, 2, 9); Array.set(arr, 3, 3); Array.set(arr, 4, 7);
Then the array elements are displayed using the for loop. A code snippet which demonstrates this is as follows −
System.out.print("The array elements are: "); for(int i: arr) { System.out.print(i + " "); }
Advertisements