用 Java 反射做點有意思的事:模擬開發環境 IDE,動態搜尋並列出任意類的成員與方法。
/*
* 這個類可以根據給定的一個 Class 位元組碼檔案,獲取類的所有資訊
* 編寫者:xiaowei
* 這個例子僅僅作為反射的練手
* 喜歡的朋友繼續完善
* 只是獲得了所有存取權限,但是沒有判斷出每個成員的權限類型
*/
import java.lang.reflect.*;
public final class FindClass
{
private String fieldList; //成員列表
private String methodList; //方法列表
private String className; //類的名字
private String showClassInfo; //輸出資訊
public void getClassField() throws Exception //獲得類的欄位
{
Field[] f = Class.forName(className).getDeclaredFields();
for(Field tem : f) //迭代 for 循環
{
tem.setAccessible(true);
this.fieldList += (tem.getType().getName() + " " + tem.getName() + ";\n");
}
}
public void getClassMethod() throws Exception //獲得類的方法
{
Method[] m = Class.forName(className).getDeclaredMethods(); //獲得類的所有定義方法
for(Method tem : m)
{
String prm = ""; //參數列表
tem.setAccessible(true);
Class[] pt = tem.getParameterTypes();
for(Class a : pt)
{
prm += (a.getName() + ",");
}
if(prm.equals("") == false)
prm = prm.substring(0, prm.length() - 1);
this.methodList += (tem.getReturnType().getName() + " " + tem.getName()
+ "(" + prm + ");\n");
}
}
public void showClassInfo() //輸出類的資訊
{
System.out.println(this.fieldList);
System.out.println(this.methodList);
}
public void getClassInfo() throws Exception //獲得類的資訊
{
this.getClassField();
this.getClassMethod();
}
public void loadClassForname(String classname) throws Exception //載入類的名字
{
this.initClassInfo();
this.className = classname;
getClassInfo();
}
public void initClassInfo() //初始化
{
this.methodList = "Method List:\n";
this.fieldList = "Field List:\n";
this.className = "";
this.showClassInfo = "";
}
public static void main(String[] args) throws Exception
{
FindClass cls = new FindClass();
cls.loadClassForname("java.lang.String"); //載入一個類
cls.showClassInfo(); //顯示類成員
}
}
class Me
{
int a;
int b;
void c(int a, int c) { }
void aa(int a) { }
}
整個範例只用了三個反射方法:Class.forName() 載入目標類;getDeclaredFields() 取得所有自行宣告的欄位;getDeclaredMethods() 取得所有自行宣告的方法。再配合 setAccessible(true) 繞過存取權限檢查,就能把 private 成員也一併列出來。
目前版本還有一個明顯的不足:只列出成員與方法的型別、名稱和參數,尚未判斷每個成員各自的權限修飾符(public、protected、private)。想補上這塊,可以透過 Field.getModifiers() 搭配 Modifier.toString() 來處理,有興趣的朋友不妨繼續完善。