Blog
It's a Wonderful Life
使用反射机制打印类声明
使用反射机制打印类的域(Field),构造器(Constructor),和方法(Method)。
package com.leo.test;
import java.lang.reflect.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Leo
*/
public class test
{
/**
*
* @param args input class name
*/
public static void main(String[] args)
{
String name;
if (args.length > 0)
{
name = args[0];
}
else
{
Scanner s = new Scanner(System.in);
System.out.println("Please input a class name (eg. java.util.Date)");
name = s.next();
}
try
{
Class cl = Class.forName(name);
Class superCl = cl.getSuperclass();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.print("class " + name + " ");
if (superCl != null && superCl != Object.class)
System.out.print("extends " + superCl.getName());
System.out.print("\n{\n");
printFields(cl);
System.out.println();
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println("}");
}
catch (ClassNotFoundException ex)
{
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
*
* @param cl class name
*/
public static void printFields(Class cl)
{
Field[] fields;
fields = cl.getDeclaredFields();
for (Field f : fields)
{
Class type = f.getType();
String name = f.getName();
System.out.print(" ");
String modifiers = Modifier.toString(f.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.print(type.getName() + " ");
System.out.println(name);
}
}
public static void printConstructors(Class cl)
{
Constructor[] cons;
cons = cl.getDeclaredConstructors();
for (Constructor c : cons)
{
System.out.print(" ");
String modifiers = Modifier.toString(c.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
System.out.print(c.getName() + " (");
Class[] params = c.getParameterTypes();
for (int i = 0; i < params.length; i++)
{
if (i > 0) System.out.print(", ");
System.out.print(params[i].getName());
}
System.out.println(")");
}
}
public static void printMethods(Class cl)
{
Method[] methods;
methods = cl.getDeclaredMethods();
for (Method m : methods)
{
System.out.print(" ");
String modifiers = Modifier.toString(m.getModifiers());
if (modifiers.length() > 0) System.out.print(modifiers + " ");
Class ret = m.getReturnType();
System.out.print(ret.getName() + " ");
System.out.print(m.getName() + " (");
Class[] params = m.getParameterTypes();
for (int i = 0; i < params.length; i++)
{
if (i > 0) System.out.print(", ");
System.out.print(params[i].getName());
}
System.out.println(")");
}
}
}