识别阵列类型
可以通过调用Class.isArray()来标识数组类型。要获得Class,请使用此跟踪的检索类对象部分中描述的方法之一。
ArrayFind示例标识命名类中数组类型的字段,并报告每个字段的组件类型。
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import static java.lang.System.out;
public class ArrayFind {
public static void main(String... args) {
boolean found = false;
try {
Class<?> cls = Class.forName(args[0]);
Field[] flds = cls.getDeclaredFields();
for (Field f : flds) {
Class<?> c = f.getType();
if (c.isArray()) {
found = true;
out.format("%s%n"
+ " Field: %s%n"
+ " Type: %s%n"
+ " Component Type: %s%n",
f, f.getName(), c, c.getComponentType());
}
}
if (!found) {
out.format("No array fields%n");
}
// production code should handle this exception more gracefully
} catch (ClassNotFoundException x) {
x.printStackTrace();
}
}
}
Class.getName()中描述了返回值Class.get*Type()
的语法。类型名称开头的'[
'字符数表示数组的维数(即嵌套深度)。
输出 samples 如下。用户 Importing 以斜体显示。基本类型byte
的数组:
$java ArrayFind java.nio.ByteBuffer
final byte[] java.nio.ByteBuffer.hb
Field: hb
Type: class [B
Component Type: byte
引用类型StackTraceElement的数组:
$ java ArrayFind java.lang.Throwable
private java.lang.StackTraceElement[] java.lang.Throwable.stackTrace
Field: stackTrace
Type: class [Ljava.lang.StackTraceElement;
Component Type: class java.lang.StackTraceElement
predefined
是参考类型java.awt.Cursor的一维数组,而cursorProperties
是参考类型String的二维数组:
$ java ArrayFind java.awt.Cursor
protected static java.awt.Cursor[] java.awt.Cursor.predefined
Field: predefined
Type: class [Ljava.awt.Cursor;
Component Type: class java.awt.Cursor
static final java.lang.String[][] java.awt.Cursor.cursorProperties
Field: cursorProperties
Type: class [[Ljava.lang.String;
Component Type: class [Ljava.lang.String;