利用Java的反射机制可以对Java类进行解析。本程序以类名为输出参数,输出该类的名称、继承的父类、实现的接口、包含的域、拥有的构造器以及方法,以及该类的继承链。
代码如下:
package chapter5;
import java.util.*;
import java.lang.reflect.*;
/**
* This program uses reflection to print all features of a class.
*
* @version 1.1 2016-12-05
* @author Zhang Yufei
*
*/
public class ReflectionTest {
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
// read class name from command line args or user input
String name;
if (args.length > 0) {
name = args[0];
} else {
Scanner scan = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Date):");
name = scan.next();
scan.close();
}
try {
// print class name and super class name (if != object)
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
Class[] interfaces = cl.getInterfaces();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0) {
System.out.print(modifiers);
}
// is class or interface
if (!cl.isInterface()) {
System.out.print(" class ");
}
printType(cl);
if (supercl != null && supercl != Object.class) {
System.out.print(" extends ");
printType(supercl);
}
if (interfaces.length > 0) {
System.out.print(" implements ");
for (int j = 0; j < interfaces.length; j++) {
if (j > 0) {
System.out.print(", ");
}
printType(interfaces[j]);