Building Arrays Using Reflection

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Building Arrays Using Reflection

This Java example program shows how to use reflection to build Arrays.

[edit] Java Source Code

  • Package: example.array
  • File: ArrayCreate.java
package example.array;
 
import java.lang.reflect.Array;
import java.util.Random;
 
public class ArrayCreate {
    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);
	}
    }
}

[edit] What Result You Can Get

Run the program, you will get:

Array of: int
Array size: 3
Position: 0, value: -496378247
Position: 1, value: 150903981
Position: 2, value: 2112539308

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools