This section provides a tutorial example on how to reflec arrays as classes and introspect its properties like superclass, element type, etc.
Arrays are represented as classes in JVM:
All arrays of the same element type and the same dimension are instances of one array class.
On a array class, the getComponentType() method returns the class type of its elements.
The element class type of a multiple dimension array is an array class.
Here is tutorial example program showing you some array classes:
/**
* ClassArrayReflection.java
* Copyright (c) 2010 by Dr. Herong Yang, herongyang.com
*/
import java.lang.reflect.*;
class ClassArrayReflection {
static java.io.PrintStream out = System.out;
public static void main(String[] a) {
out.println("");
out.println(" byte[] class information...");
byte[] b = new byte[10];
arrayIntrospection(b.getClass());
out.println("");
out.println(" int[] class information...");
int[] i = new int[100];
arrayIntrospection(i.getClass());
out.println("");
out.println(" byte[][] class information...");
byte[][] bb = new byte[10][100];
arrayIntrospection(bb.getClass());
}
public static void arrayIntrospection(Class cls) {
out.println("Class name:");
out.println(" "+cls.getName());
Class p = cls.getSuperclass();
out.println("Parent class:");
out.println(" "+p);
Class t = cls.getComponentType();
out.println("Element type:");
out.println(" "+t.getName());
Constructor[] c = cls.getDeclaredConstructors();
out.println("Constructors:");
for (int i = 0; i<c.length; i++)
out.println(" "+c[i].toString());
Field[] f = cls.getDeclaredFields();
out.println("Fields:");
for (int i = 0; i<f.length; i++)
out.println(" "+f[i].toString());
Method[] m = cls.getDeclaredMethods();
out.println("Methods:");
for (int i = 0; i<m.length; i++)
out.println(" "+m[i].toString());
}
}
When executed on my Windows XP system with JDK 1.6.0,
I got this result:
C:\herong\jvm\cod>java ClassArrayReflection
byte[] class information...
Class name:
[B
Parent class:
class java.lang.Object
Element type:
byte
Constructors:
Fields:
Methods:
int[] class information...
Class name:
[I
Parent class:
class java.lang.Object
Element type:
int
Constructors:
Fields:
Methods:
byte[][] class information...
Class name:
[[B
Parent class:
class java.lang.Object
Element type:
[B
Constructors:
Fields:
Methods:
The result tells me that:
Array classes are subclasses of java.lang.Object.
Array classes have no constructors, no fields, and no methods.