Java Reflection API 运用示例
图5示范图4提过的每一个Reflection API,及其执行结果。程序中出现的tName()是个辅助函数,可将其第一自变量所代表的“Java class完整路径字符串”剥除路径部分,留下class名称,储存到第二自变量所代表的一个hashtable去并返回(如果第二自变量为null,就不储存而只是返回)。
#001 Class c = null;
#002 c = Class.forName(args[0]);
#003
#004 Package p;
#005 p = c.getPackage();
#006
#007 if (p != null)
#008 System.out.println("package "+p.getName()+";");
执行结果(例):
package java.util;
图5-1:找出class 隶属的package。其中的c将继续沿用于以下各程序片段。
#001 ff = c.getDeclaredFields();
#002 for (int i = 0; i < ff.length; i++)
#003 x = tName(ff[i].getType().getName(), classRef);
#004
#005 cn = c.getDeclaredConstructors();
#006 for (int i = 0; i < cn.length; i++) {
#007 Class cx[] = cn[i].getParameterTypes();
#008 for (int j = 0; j < cx.length; j++)
#009 x = tName(cx[j].getName(), classRef);
#010 }
#011
#012 mm = c.getDeclaredMethods();
#013 for (int i = 0; i < mm.length; i++) {
#014 x = tName(mm[i].getReturnType().getName(), classRef);
#015 Class cx[] = mm[i].getParameterTypes();
#016 for (int j = 0; j < cx.length; j++)
#017 x = tName(cx[j].getName(), classRef);
#018 }
#019 classRef.remove(c.getName()); //不必记录自己(不需import 自己)
执行结果(例):
import java.util.ListIterator;
import java.lang.Object;
import java.util.LinkedList$Entry;
import java.util.Collection;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
图5-2:找出导入的classes,动作细节详见内文说明。
#001 int mod = c.getModifiers();
#002 System.out.print(Modifier.toString(mod)); //整个modifier
#003
#004 if (Modifier.isInterface(mod))
#005 System.out.print(" "); //关键词 "interface" 已含于modifier
#006 else
#007 System.out.print(" class "); //关键词 "class"
#008 System.out.print(tName(c.getName(), null)); //class 名称
执行结果(例):
public class LinkedList
图5-3:找出class或interface 的名称,及其属性(modifiers)。
#001 TypeVariable<Class>[] tv;
#002 tv = c.getTypeParameters(); //warning: unchecked conversion
#003 for (int i = 0; i < tv.length; i++) {
#004 x = tName(tv[i].getName(), null); //例如 E,K,V...
#005 if (i == 0) //第一个
#006 System.out.print("<" + x);
#007 else //非第一个
#008 System.out.print("," + x);
#009 if (i == tv.length-1) //最后一个
#010 System.out.println(">");
#011 }
执行结果(例):
public abstract interface Map<K,V>
或 public class LinkedList<E>
图5-4:找出parameterized types 的名称
#001 Class supClass;
#002 supClass = c.getSuperclass();
#003 if (supClass != null) //如果有super class
#004 System.out.print(" extends" +
#005 tName(supClass.getName(),classRef));
执行结果(例):
public class LinkedList<E>
extends AbstractSequentialList,
图5-5:找出base class。执行结果多出一个不该有的逗号于尾端。此非本处重点,为简化计,不多做处理。
#001 Class cc[];
#002 Class ctmp;
#003 //找出所有被实现的interfaces
#004 cc = c.getInterfaces();
#005 if (cc.length != 0)
#006 System.out.print(", \r\n" + " implements "); //关键词
#007 for (Class cite : cc) //JDK1.5 新式循环写法
#008 System.out.print(tName(cite.getName(), null)+", ");
执行结果(例):