- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Create integer array with Array.newInstance in Java
- Create new instance of an Array with Java Reflection Method
- Create new instance of a Two-Dimensional array with Java Reflection Method
- Initialize an Array with Reflection Utilities in Java
- Use reflection to create, fill, and display an array in Java
- Reflection Array Class in Java
- Create array with MongoDB query?
- How to instantiate a static inner class with reflection in Java?
- Using reflection to check array type and length in Java
- Java Program to create an array with randomly shuffled numbers in a given range
- Reading Attributes with Reflection API in PHP 8
- How to declare Java array with array size dynamically?
- Create LabelValue Tuple using with() method in Java
- Create KeyValue Tuple using with() method in Java
- Create Octet Tuple using with() method in Java

Advertisements