《Java核心技术 卷I》 一 Java中利用反射打印一个类的所有信息

package myJavaproject;

/**
*代码来源:Java核心技术 卷I
*只为分享给他人,而将代码奉上
*/
import java.util.*;
import java.lang.reflect.*;

public class ReflectionTest {

	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 (e.g.java.Date):");
			name = in.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");
            //打印类的构造函数
			printConstructors(cl);
			System.out.println();
            //打印类的方法
			printMethods(cl);
			System.out.println();
            //打印类的域
			printFields(cl);
			System.out.println("}");
		}catch(ClassNotFoundException e) {
			e.printStackTrace();
		}
		System.exit(0);
	}

	//打印类的构造函数
	public static void printConstructors(Class cl) {

        //获得所有的构造函数并存放在数组中
		Constructor[] constructors = cl.getDeclaredConstructors();
        //获得函数修饰符和所需要的域并打印
		for(Constructor c:constructors) {
			String name = c.getName();
			System.out.print("    ");
			String modifiers = Modifier.toString(c.getModifiers());
			if(modifiers.length()>0) {
				System.out.print(modifiers+" ");
			}
			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(");");
		}	
	}
	
    //打印类的方法
	public static void printMethods(Class cl) {
		Method[] methods = cl.getDeclaredMethods();
		for(Method m:methods) {
            //获取返回值类型并自动装包
			Class retType = m.getReturnType();
			String name = m.getName();
			System.out.print("    ");
			String modifiers = Modifier.toString(m.getModifiers());
			if(modifiers.length()>0) {
				System.out.print(modifiers+" ");
			}
			System.out.print(retType.getName()+" "+name+"(");
			Class[] paramTypes = m.getParameterTypes();
			for(int j = 0;j<paramTypes.length;j++) {
				if(j>0) {
					System.out.print(", ");
					
				}
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}	
	}

    //打印类的域
	public static void printFields(Class cl) {
		Field[] 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.println(type.getName()+" "+name+";");
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41750725/article/details/81239195