Java - Expanding an Array via Reflection

Introduction

An array in Java is a fixed-length data structure.

You can use the combination of the getComponentType() method of the Class class and the newInstance() method of the Array class to create a new array of a type.

Then you can use the arraycopy() static method of the System class to copy the old array elements to the new array.

The following code illustrates how to create an array of a particular type using reflection.

Demo

import java.lang.reflect.Array;
import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    // Create an array of length 2
    int[] ids = { 1, 2 };

    System.out.println("Old array length: " + ids.length);
    System.out.println("Old array elements:" + Arrays.toString(ids));

    // Expand the array by 1
    ids = (int[]) expandBy(ids, 1);

    // Set the third element to 103
    ids[2] = 103; // This is newly added element
    System.out.println("New array length: " + ids.length);
    System.out.println("New array elements:" + Arrays.toString(ids));
  }//from   w  ww . j a  v a 2 s.co m

  public static Object expandBy(Object oldArray, int increment) {
    Object newArray = null;

    // Get the length of old array using reflection
    int oldLength = Array.getLength(oldArray);
    int newLength = oldLength + increment;

    // Get the class of the old array
    Class<?> c = oldArray.getClass();

    // Create a new array of the new length
    newArray = Array.newInstance(c.getComponentType(), newLength);

    // Copy the old array elements to new array
    System.arraycopy(oldArray, 0, newArray, 0, oldLength);

    return newArray;
  }
}

Result

Related Topic