Thursday, September 23, 2010

Retrieving Component Types using reflection in java

The component type is the type of an array's elements. For example, the component type of the arrowKeys array in the following line of code is Button:
Button[] arrowKeys = new Button[4];
The component type of a multi-dimensional array is an array. In the next line of code, the component type of the array named matrix is int[]:
int[][] matrix = new int[100][100];
By invoking the getComponentType method against the Class object that represents an array, you can retrieve the component type of the array's elements. The sample program that follows invokes the getComponentType method and prints out the class name of each array's component type.
import java.lang.reflect.*;
import java.awt.*;

class SampleComponent {

public static void main(String[] args) {
int[] ints = new int[2];
Button[]  buttons = new Button[6];
String[][] twoDim = new String[4][5];

printComponentType(ints);
printComponentType(buttons);
printComponentType(twoDim);
}

static void printComponentType(Object array) {
Class arrayClass = array.getClass();
String arrayName = arrayClass.getName();
Class componentClass = arrayClass.getComponentType();
String componentName = componentClass.getName();
System.out.println("Array: " + arrayName + 
", Component: " + componentName);
}
}

The output of the sample program is:
Array: [I, Component: int
Array: [Ljava.awt.Button;, Component: java.awt.Button
Array: [[Ljava.lang.String;, Component: [Ljava.lang.String;

No comments:

Post a Comment

Chitika