163. Working with arrays

The Java Reflection API comes with a class dedicated to working with arrays. This class is named java.lang.reflect.Array.

For example, the following snippet of code creates an array of int. The first parameter tells what type each element in the array should be of. The second parameter represents the length of the array. Therefore, an array of 10 integers can be defined via Array.newInstance() as follows:

int[] arrayOfInt = (int[]) Array.newInstance(int.class, 10);

Using Java Reflection, we can alter the content of an array. There is a general set() method and a bunch of setFoo() methods (for example, setInt(), and setFloat()). Setting the value at index 0 to 100 can be done as follows:

Array.setInt(arrayOfInt, 0, 100);

Fetching a value from an array can be accomplished via the get() and getFoo() methods (these methods get the array and the index as arguments and return the value from the specified index):

int valueIndex0 = Array.getInt(arrayOfInt, 0);

Getting the Class of an array can be done as follows:

Class<?> stringClass = String[].class;
Class<?> clazz = arrayOfInt.getClass();

And we can extract the type of the array via getComponentType():

// int
Class<?> typeInt = clazz.getComponentType();

// java.lang.String
Class<?> typeString = stringClass.getComponentType();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.11.227