Saturday 16 August 2014

Reflections and Arrays

By using java.lang.reflect.Array class, you can create and access arrays.

Creating Arrays
Array class provides newInstance method to create single and multi dimensional arrays.

public static Object newInstance(Class<?> componentType, int length)
public static Object newInstance(Class<?> componentType, int... dimensions)

Example
int[] arr1 = (int[])Array.newInstance(int.class, 10);
int[][] arr2 = (int[][])Array.newInstance(int.class, 5,5);

Assign values to Array
Array class provides set method, to set values to array.

public static native void set(Object array, int index, Object value)

Get the Values of Array
Array class provide 'get' method to get the elements of an array.

public static native Object get(Object array, int index)

import java.lang.reflect.Array;

public class CreateArray {
    public static void main(String args[]){
        int[] arr1 = (int[])Array.newInstance(int.class, 10);
        
        for(int i=0; i<10; i++)
            Array.set(arr1, i, i);
        
        for(int i=0; i<10; i++)
            System.out.println(Array.get(arr1, i));
    }
}

Output
0
1
2
3
4
5
6
7
8
9




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment