Java程序工具之发射机制类信息打印器(Java版本)
来源:互联网 发布:淘宝自动回复怎么设置 编辑:程序博客网 时间:2024/06/04 20:11
/** * @author Sking * 使用反射机制打印类信息 */package component.ReadAPI;import java.lang.reflect.*;import java.util.*;public class GenericReflectionTest{ 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.Date): "); name = in.next();//从控制台读取指定类 } try { Class<?> cl = Class.forName(name);//返回指定类对应的Class对象 printClass(cl);//打印类声明 for (Method m : cl.getDeclaredMethods())//打印类的所有方法 printMethod(m); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void printClass(Class<?> cl) { System.out.print(cl);//打印类名,格式为:class 类的完全限定名 printTypes(cl.getTypeParameters(), "<", ", ", ">");//类的类型参数列表 Type sc = cl.getGenericSuperclass(); //返回直接父类的类型 if (sc != null) { System.out.print(" extends "); printType(sc); } printTypes(cl.getGenericInterfaces(), " implements ", ", ", ""); 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(), "<", ", ", "> ");//方法类型参数列表 printType(m.getGenericReturnType());//打印返回类型 System.out.print(" "); System.out.print(name);//打印方法名 System.out.print("("); printTypes(m.getGenericParameterTypes(), "", ", ", "");//形参类型列表 System.out.println(")"); } /** * 按照指定格式打印数组参数指定的类型列表 * @param types 类型数组 * @param pre 格式前缀 * @param sep 类型之间的分隔符 * @param suf 格式后缀 */ public static void printTypes(Type[] types, String pre, String sep, String suf) { 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]); } if (types.length > 0) System.out.print(suf); } public static void printType(Type type) { if (type instanceof Class) //对象类型 { Class<?> t = (Class<?>) type; System.out.print(t.getName()); } else if (type instanceof TypeVariable)//类型变量 { TypeVariable<?> t = (TypeVariable<?>) type; System.out.print(t.getName()); printTypes(t.getBounds(), " extends ", " & ", ""); } else if (type instanceof WildcardType)//通配符类型表达式 { WildcardType t = (WildcardType) type; System.out.print("?"); printTypes(t.getLowerBounds(), " extends ", " & ", ""); printTypes(t.getUpperBounds(), " super ", " & ", ""); } else if (type instanceof ParameterizedType)//参数化类型 { ParameterizedType t = (ParameterizedType) type; Type owner = t.getOwnerType(); if (owner != null) { printType(owner); System.out.print("."); } printType(t.getRawType()); printTypes(t.getActualTypeArguments(), "<", ", ", ">"); } else if (type instanceof GenericArrayType)//数组类型 { GenericArrayType t = (GenericArrayType) type; System.out.print(""); printType(t.getGenericComponentType()); System.out.print("[]"); } }}