[b]使用Java反射机制得到类的结构信息[/b]
代码如下:
代码如下:
package com.youdao.wm;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* java反射机制测试:打印类的构造函数、方法、属性的信息
*
* @author jacky
*
*/
public class ReflectionTest {
public static void main(String[] args) {
// 要打印的类名
String name = "java.lang.Double";
try {
// 得到此类对应的Class
Class c1 = Class.forName(name);
// 得到此类的父类
Class superc1 = c1.getSuperclass();
System.out.print("class " + name);
// 如果超类不为空且不是Object
if (superc1 != null && superc1 != Object.class) {
System.out.print("extends " + superc1.getName());
}
System.out.print("\n{\n");
// 打印此类的构造函数信息
printConstructors(c1);
System.out.println();
// 打印此类的方法信息
printMethods(c1);
System.out.println();
// 打印此类的属性信息
printFields(c1);
System.out.print("\n}\n");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 打印Class对应类的构造函数信息
*
* @param c1
* Class
*/
public static void printConstructors(Class c1) {
Constructor[] constructors = c1.getDeclaredConstructors();
for (Constructor c : constructors) {
String name = c.getName();
System.out.print(" " + Modifier.toString(c.getModifiers()));
System.out.print(" " + name + "(");
Class[] paramTypes = c.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0)
System.out.print(",");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
* 打印Class对应类的所有方法信息
*
* @param c1
* Class
*/
public static void printMethods(Class c1) {
Method[] methods = c1.getDeclaredMethods();
for (Method method : methods) {
Class retType = method.getReturnType();
String name = method.getName();
System.out.print(" " + Modifier.toString(method.getModifiers()));
System.out.print(" " + retType.getName() + " " + name + "(");
Class[] paramTypes = method.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0)
System.out.print(", ");
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
/**
* 打印Class对应类的属性信息
*
* @param c1
* Class
*/
public static void printFields(Class c1) {
Field[] fields = c1.getDeclaredFields();
for (Field f : fields) {
Class classType = f.getType();
System.out.print(" " + Modifier.toString(f.getModifiers()));
System.out.print(" " + classType.getName() + " " + f.getName());
System.out.println(";\n");
}
}
}