Fill and display an array

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

public class MainClass {
  public static void main(String args[]) {
    Object array = Array.newInstance(int.class, 3);
    printType(array);
    fillArray(array);
    displayArray(array);
  }

  private static void printType(Object object) {
    Class type = object.getClass();
    if (type.isArray()) {
      Class elementType = type.getComponentType();
      System.out.println("Array of: " + elementType);
      System.out.println("Array size: " + Array.getLength(object));
    }
  }

  private static void fillArray(Object array) {
    int length = Array.getLength(array);
    Random generator = new Random(System.currentTimeMillis());
    for (int i = 0; i < length; i++) {
      int random = generator.nextInt();
      Array.setInt(array, i, random);
    }
  }

  private static void displayArray(Object array) {
    int length = Array.getLength(array);
    for (int i = 0; i < length; i++) {
      int value = Array.getInt(array, i);
      System.out.println("Position: " + i + ", value: " + value);
    }
  }
}
  
Home 
  Java Book 
    Runnable examples  

Reflection Array:
  1. Create an array of 10 ints.
  2. Create a 10x20 2-dimensional int array
  3. Fill and display an array
  4. Get and Set the Value of an Element in an Array Object
  5. Get array(component) type
  6. Get array dimensions
  7. Get array length
  8. Get array name and type
  9. Is an Object an Array