Reflection Array Class in Java

Java 8Server Side ProgrammingProgramming

The array class present in java.lang.reflect package belong to the Java reflection class. The Java Reflection class provides static methods, and these methods can be used to create and access Java arrays in a dynamic manner. This class is final, and this means it can’t be changed or even instantiated. The methods present inside this class can be used with the help of the class name itself.

The methods present in java.util.Arrays.class can be used to work with arrays, and the java.lang.reflect.Array class contains methods that help in creating and working with Java arrays in a dynamic manner.

The java.lang.reflect.Array class is a child of the java.lang.Object class, which is its parent class. It can be declared as follows −

public final class Array extends Object
Array.function_name;
…

Below is a simple implementation of creating an array of a specific size using the concept of reflection −

Example

 Live Demo

import java.lang.reflect.Array;
import java.util.Arrays;
public class Demo {
   public static void main(String[] args) {
      int array_size = 6;
      int[] int_array = (int[])Array.newInstance(int.class, array_size);
      System.out.println(Arrays.toString(int_array));
   }
}

Output

[0, 0, 0, 0, 0, 0]

A class named Demo contains the main function, where an array size is defined. An integer array is defined by specifying the class of the array, and the size of the array. This array is printed on the screen. The output is an array of 5 zeroes, since the size was 5, and no element was specified, thereby taking the default value of 0.

raja
Published on 14-Sep-2020 12:56:40
Advertisements