您的位置:首页 > 编程语言 > Java开发

Java反射的高级应用,模拟开发环境IDE动态搜索类成员以及方法,。。。。。

2012-01-15 23:38 726 查看
/*

*这个类可以根据 给定的一个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)

{

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐