用JAVA反射获得任意类的内部结构

来源:互联网 发布:跨服务器访问数据库 编辑:程序博客网 时间:2024/05/10 00:38
package chapter12.PairTest3;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.lang.reflect.TypeVariable;import java.util.Arrays;import java.util.Scanner;public class Test {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.util.Collections): ");name = in.next();}try {Class<?> cl = Class.forName(name);printClass(cl);for (Method m : cl.getDeclaredMethods()) {printMethod(m);}} catch (ClassNotFoundException e) {e.printStackTrace();}}public static void printClass(Class<?> cl) {System.out.print("class " + cl.getSimpleName());printTypes(cl.getTypeParameters(), "<", ", ", ">", true);Type sc = cl.getGenericSuperclass();if (sc != null) {System.out.print(" extends ");printType(sc, false);}printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false);System.out.println();}public static void printMethod(Method m) {String name = m.getName();System.out.print(Modifier.toString(m.getModifiers()));System.out.print(" ");printTypes(m.getTypeParameters(), "<", ", ", ">", true);printType(m.getGenericReturnType(), false);System.out.print(" ");System.out.print(m.getName());System.out.print("(");printTypes(m.getGenericParameterTypes(), "", ", ", "", false);System.out.println(")");}/*** * 打印所有类型参数 * @param types 类型变量数组 */public static void printTypes(Type[] types, String pre, String sep, String suf,boolean isDefinition) {// 没有上边界则返回if (pre.equals(" extends ") && Arrays.equals(types, new Type[] { Object.class }))return;if (types.length > 0)System.out.print(pre);// 遍历所有类型变量for (int i = 0; i < types.length; i++) {if (i > 0)System.out.print(sep);printType(types[i], isDefinition);}if (types.length > 0)System.out.print(suf);}// 打印单个类型参数public static void printType(Type type, boolean isDefinition) {if (type instanceof Class) {Class<?> t = (Class<?>) type;System.out.print(t.getSimpleName());} else if (type instanceof TypeVariable) {TypeVariable<?> t = (TypeVariable<?>) type;System.out.print(t.getName());if (isDefinition)// 打印类型变量的上边界printTypes(t.getBounds(), " extends ", " & ", "", false);} else if (type instanceof ParameterizedType) {// 如果是参数化类型ParameterizedType t = (ParameterizedType) type;Type owner = t.getOwnerType();if (owner != null) {printType(owner, false);System.out.print(".");}printType(t.getRawType(), false);printTypes(t.getActualTypeArguments(), "<", ", ", ">", false);}}}