Arrays Ext
Scenario:
Our colleague has just finished writing his code and at end of his code, an
array is passed to our code. We must carry out some operations on the elements
of the array. Since the array could possibly contain various types of objects,
we cannot carry out our operations on all the objects. Instead, we’d like pass
in a Class object for the type of the object we would like to our on. We would
like to create an array from the original array containing only the elements we
want.
Solution:
The heart of code for the arrayExt
class is the arExt method. This
method takes an object, which is our array, and a Class
object, which is the class object of the elements that we want to extract. The
first if statement checks if
the object we were sent is an array. If it is an array, we get its length so
that we can go through the array and check each element. The for
loop extracts an element out of the array object and then it checks if the element
extracted can be assigned to an object of
Class
c, which is a parameter of this method. Seeing if it can be assigned to
an object of Class c, we are able
to extract elements of the type represented by
Class c. It is the same type, it is added to a list,
which keeps track of all the elements from our array that we are looking for.
arExt method:
public static List arExt(Object arr, Class c){
List ext = new LinkedList();
Class g = arr.getClass();if(arr.getClass().isArray()) {
int length = Array.getLength(arr);
for(int i=0;i<length;i++) {Object elm = Array.get(arr,i);
if(c.isAssignableFrom(elm.getClass())) ext.add(elm);}
return ext;} else {
throw new IllegalArgumentException("Invalid Argument");
}
}
Conclusion:
This example illustrates that we can use Reflection to extract elements of
a certain type, which we specified at run-time. Without Reflection, we would
be unable to compare the object of the array to a certain type. The use of Reflection
has made it much easier to examine the array and add on the objects to a list.