歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java反射的高級應用,模擬開發環境IDE動態搜索類成員以及方法

Java反射的高級應用,模擬開發環境IDE動態搜索類成員以及方法

日期:2017/3/1 10:38:34   编辑:Linux編程

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)
{

}
}

Copyright © Linux教程網 All Rights Reserved