最大可容纳20组数据 给出一个显示类各成员的小程序 import java.lang.reflect.*; import javax.swing.*; public class Reflection{ public static void main(String[] args){ String name; if(args.length>0) name=args[0]; else name=JOptionPane.showInputDialog("input a class name(e.g java.util.Date):"); try{ Class cl=Class.forName(name); Class supercl=cl.getSuperclass(); Class[] c=cl.getInterfaces(); if(!cl.isInterface()){ System.out.print("class "); } else System.out.print("interface "); System.out.print(cl.getName().substring(cl.getName().lastIndexOf('.')+1)); if(supercl!=null&&supercl!=Object.class) System.out.print(" extends "+supercl.getName().substring( supercl.getName().lastIndexOf('.')+1)); if(c.length>0){ if(cl.isInterface()){ for(int i=0;i<c.length;i++){ System.out.print(" extents "+c[i].getName().substring( c[i].getName().lastIndexOf('.')+1)); } } else{ System.out.print(" implements "); for(int i=0;i<c.length;i++){ if(i>0)System.out.print(","); System.out.print(c[i].getName().substring(c[i].getName().lastIndexOf('.')+1)); } } } System.out.print("{\n"); printConstructors(cl); System.out.println(); printMethods(cl); System.out.println(); printFields(cl); System.out.println("}"); } catch(ClassNotFoundException e){ e.printStackTrace(); } } public static void printConstructors(Class cl){ Constructor[] cons=cl.getDeclaredConstructors(); for(int i=0;i<cons.length;i++){ String name=cons[i].getName(); int a=name.lastIndexOf('.'); String name1=name.substring(a+1); System.out.print(Modifier.toString(cons[i].getModifiers())); System.out.print(" "+name1+"("); Class[] paramTypes=cons[i].getParameterTypes(); for(int j=0;j<paramTypes.length;j++){ if(j>0)System.out.print(","); System.out.print(paramTypes[j].getName().substring(paramTypes[j].getName ().lastIndexOf('.')+1)); } System.out.println(");"); } } public static void printMethods(Class cl){ Method[] methods=cl.getDeclaredMethods(); for(int i=0;i<methods.length;i++){ Method m=methods[i]; Class r=m.getReturnType(); String name=Modifier.toString(m.getModifiers()); System.out.print(Modifier.toString(m.getModifiers())); System.out.print(" "+r.getName().substring(r.getName( ).lastIndexOf('.')+1)+" "+m.getName()+"("); Class[] p=m.getParameterTypes(); for(int j=0;j<p.length;j++){ if(j>0)System.out.print(","); System.out.print(p[j].getName().substring(p[j].getName().lastIndexOf('.')+1)); } System.out.println(");"); } } public static void printFields(Class cl){ Field[] fields=cl.getDeclaredFields(); for(int i=0;i<fields.length;i++){ Field f=fields[i]; String name=f.getName(); String type=f.getType().getName().substring(f.getType().getName().lastIndexOf('.')+1); System.out.print(Modifier.toString(f.getModifiers())); System.out.println(" "+type+" "+name+";"); } } } (责任编辑:laiquliu) |