Trail: The Reflection API
|
Lesson: Working with Arrays
|
|
Getting and Setting Element Values
In most programs, to access array elements you merely use an assignment
expression as follows:
int[10] codes;
codes[3] = 22;
aValue = codes[3];
This technique will not work if you don't know the name of the array until runtime.
Fortunately, you can use the Array class set and get methods to access
array elements when the name of the array is unknown at compile time. In
addition to get and set, the Array class has specialized methods that work
with specific primitive types. For example, the value parameter of setInt is
an int, and the object returned by getBoolean is a wrapper for a boolean
type.
The sample program that follows
uses the set and get methods to copy the
contents of one array to another.
import java.lang.reflect.*;
class SampleGetArray {
public static void main(String[] args) {
int[] sourceInts = {12, 78};
int[] destInts = new int[2];
copyArray(sourceInts, destInts);
String[] sourceStrgs = {"Hello ", "there ", "everybody"};
String[] destStrgs = new String[3];
copyArray(sourceStrgs, destStrgs);
}
public static void copyArray(Object source, Object dest) {
for (int i = 0; i < Array.getLength(source); i++) {
Array.set(dest, i, Array.get(source, i));
System.out.println(Array.get(dest, i));
}
}
}
The output of the sample program is:
12
78
Hello
there
everybody
|