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
: The component type of a multi-dimensional array is an array. In the next line of code, the component type of the array namedButton[] arrowKeys = new Button[4];
matrix
is int[]
: By invoking theint[][] matrix = new int[100][100];
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. The output of the sample program is: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);
}
}
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