ava的反射机制中通过Class类的getComponentType()方法可以取得一个数组的Class对象,那么什么是“数组的Class对象”?
所有的JAVA类都继承自object,那数组也不例外。就是说一个数组本身就是一个class,你得到这个数组的CLASS对象后,可以把它转型为数组。
package com.test.string;
import java.awt.Button;
public class SampleComponentReflection {
public static void main(String[] args) {
int[] ints = new int[2];
Button[] buttons = new Button[6];
String[][] twoDim = new String[4][5];
String[] two = new String[4];
printComponentType(ints);
printComponentType(buttons);
printComponentType(twoDim);
printComponentType(two);
}
static void printComponentType(Object array) {
Class extends Object> arrayClass = array.getClass();
String arrayName = arrayClass.getName();
Class> componentClass = arrayClass.getComponentType();
String componentName = componentClass.getName();
System.out.println("ArrayClass:"+arrayClass+" |ArrayName: " + arrayName + "|componentName: "
+ componentName);
}
}
ArrayClass:class [I |ArrayName: [I|componentName: int
ArrayClass:class [Ljava.awt.Button; |ArrayName: [Ljava.awt.Button;|componentName: java.awt.Button
ArrayClass:class [[Ljava.lang.String; |ArrayName: [[Ljava.lang.String;|componentName: [Ljava.lang.String;
ArrayClass:class [Ljava.lang.String; |ArrayName: [Ljava.lang.String;|componentName: java.lang.String