Given a type Object, suppose we need to:
a) determine the type of the array of its various fields
b) create another array of the same type or change the size of the same array
c) retrieve/set values in the array
Given an object it is not possible to figure out type of array, create a new array, and set its value in a fairly easy manner. Roundabout ways must exist in Java to do it without Reflection but any roundabout ways defeat the purpose of using it over Reflection.
The code in MagicArrays.java uses Reflection elements we have discussed. The various parts of the source code accomplish the following:
a) We are given an object of an arbitrary type. Using Reflection, we employ introspection to retrieve the names/types/component_types of all its fields (public variables). Using these fieldTypes, we check whether each type is an array. If so, we display the type of that particular fieldType.
b) We are given an object, known to be an array, but of unknown type. We retrieve its component type, and using this, we can create a new array of length variable to the original length (note the original length can be resolved by using Array.getLength(origArray) method provided by the Reflection API.
c) We are given an object, known to be an array, but of unknown type. We can access its contents (to retrieve or put information) by using the Array.get(..) and Array.set(..) methods respectively, also provided in the Array class of the Reflection API.
The output upon running MagicArrays.java is as follows:
Radio.message is an array of type [Ljava.lang.String;
Radio.stations is an array of type [Ljava.lang.Double;
Radio.presets is an array of type [Ljava.lang.Integer;
Radio.equalizer is an array of type [Ljava.lang.Integer;
a1:1 2 3 4 5
a2:1 2 3 4 5 0 0 0 0 0
a1:-999 -999 -999 -999 -999
We could use Reflection in this sense to obtain information about an array. This is very useful in a scenario where we are being passed an array from someone's code and are not given adequate information regarding the input we are receiving.
Source Code (MagicArrays.java)