Java 反射获取类信息

//部分参考至Core Java
package reflection;

import java.lang.reflect.*;
import java.util.Scanner;

public class ReflectionTest {
	public static void printConstructers(Class c1) {
		Constructor[] ct = c1.getDeclaredConstructors();
		for(Constructor c : ct) {
			String modifier = Modifier.toString(c.getModifiers());
			System.out.print(" ");
			if(modifier.length() > 0) 
				System.out.print(modifier+" ");
			
			String name = c1.getName();
			System.out.print(name + "(");
			
			Class[] pc = c.getParameterTypes();
			for(int i=0; i 0)
					System.out.print(",");
				System.out.print(pc[i].getName());
			}
			System.out.println(");");
		}
	}
	
	public static void printMethods(Class c1) {
		Method[] ms = c1.getDeclaredMethods();
		for(Method m : ms) {
			String modifier = Modifier.toString(m.getModifiers());
			if(modifier.length() > 0)
				System.out.print(" " + modifier);
			
			System.out.print(" " + m.getReturnType() + " " + m.getName() +"(");
			
			Class[] pc = m.getParameterTypes();
			for(int i=0; i 0)
					System.out.print(",");
				System.out.print(pc[i].getName());
			}
			System.out.println(");");
		}
	}
	
	public static void printFields(Class c1) {
		Field[] fs = c1.getDeclaredFields();
		for(Field f : fs) {
			String modifier = Modifier.toString(f.getModifiers());
			if(modifier.length() > 0)
				System.out.print(" " + modifier + " ");
			System.out.println(f.getType().getName() + " " + f.getName() + ";");
			
		}
	}
	
	
	public static void main(String[] args) {
		String name;
		if(args.length > 0)
			name = args[0];
		else {
			Scanner in = new Scanner(System.in);
			System.out.println("Enter Class Name");
			name = in.next();
		}
		
		try {
			Class c1 = Class.forName(name);
			Class superc1 = c1.getSuperclass();
			String modifiers = Modifier.toString(c1.getModifiers());
			if(modifiers.length() > 0)
				System.out.print(modifiers + " ");
			System.out.print("class "+name);
			if(superc1 != null && superc1 != Object.class)
				System.out.print(" extends "+superc1.getName());
			System.out.print("\n{\n");
			printConstructers(c1);
			System.out.println();
			printMethods(c1);
			System.out.println();
			printFields(c1);
			System.out.print("}");
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
}

 

你可能感兴趣的:(JavaSE)