Java Reference
In-Depth Information
// Set the third element to 103
ids[2] = 103; // This is newly added element
System.out.println("New array length: " + ids.length);
System.out.println("New array elements:" + Arrays.toString(ids));
}
public static Object expandBy(Object oldArray, int increment) {
Object newArray = null;
// Get the length of old array using reflection
int oldLength = Array.getLength(oldArray);
int newLength = oldLength + increment;
// Get the class of the old array
Class<?> c = oldArray.getClass();
// Create a new array of the new length
newArray = Array.newInstance(c.getComponentType(), newLength);
// Copy the old array elements to new array
System.arraycopy(oldArray, 0, newArray, 0, oldLength);
return newArray;
}
}
Old array length: 2
Old array elements:[101, 102]
New array length: 3
New array elements:[101, 102, 103]
Who Should Use Reflection?
If you have used any integrated development environment (IDE) to develop a GUI application using drag-and-drop
features, you have already used an application that uses reflection in one form or another. All GUI tools that let you set
the properties of a control, say a button, at design time uses reflection to get the list of the properties for that control.
Other tools such as class browsers and debuggers also use reflection. As an application programmer, you will not
use reflection much in your programs unless you are developing advanced applications that make use of dynamism
provided by the reflection API. It should be noted that using too much reflection slows down the performance of your
application.
Summary
Reflection is the ability of a program to query and modify its state “as data” during the execution of the program. Java
represents the byte code of a class as an object of the Class class to facilitate reflection. The class fields, constructors,
and methods can be accessed as an object of the Field , Constructor , and Method classes, respectively. Using a Field
object, you can access and change the value of the field. Using a Method object, you can invoke the method. Using a
Constructor object, you can invoke the constructor. Using the Array class, you can also create arrays of a specified
type and dimension using reflection and manipulate the elements of the arrays.
 
Search WWH ::




Custom Search