Reflect Array Generic Access

Create and read arrays of unknown component type through java.lang.reflect.Array, including primitive arrays and type-checked writes.

JavaData Integrity

Code

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

public class Main {
    public static void main(String[] args) {
        // reflect.Array creates an array when only the component type is known
        Object numbers = Array.newInstance(int.class, 4);
        for (int i = 0; i < Array.getLength(numbers); i++) {
            Array.setInt(numbers, i, i * i);
        }
        System.out.println("int array: " + Arrays.toString((int[]) numbers));
        System.out.println("component: " + numbers.getClass().getComponentType());

        Object names = Array.newInstance(String.class, 3);
        Array.set(names, 0, "ada");
        Array.set(names, 1, "bob");
        System.out.println("names[0]: " + Array.get(names, 0));
        System.out.println("names length: " + Array.getLength(names));

        // a wrong element type is rejected instead of silently converted
        try {
            Array.set(names, 2, Integer.valueOf(7));
        } catch (IllegalArgumentException e) {
            System.out.println("type mismatch rejected: " + e.getClass().getSimpleName());
        }
    }
}

How it works

Reflect Array Generic Access is built around the class Main and the function main.

One loop does the cycling here: for (int i = 0; i < Array.getLength(numbers); i++).

Caveats

  • No external surface: all behavior comes from the standard library.

Putting it to use

Signature: public static void main(String[] args)

The steps announce themselves in the output — int array:, component:, names[0]: — when the file runs.

Core lines

Object names = Array.newInstance(String.class, 3);
Object numbers = Array.newInstance(int.class, 4);
Array.set(names, 2, Integer.valueOf(7));

Interactive Tools for This Topic

FAQ

What does Reflect Array Generic Access print when run?
No setup needed: run the file and look for labeled lines like `int array:`, `component:`, `names[0]:` in the output.