java反射机制超简单Demo

Demo里包括构造方法的获取,使用反射机制新建对象,成员变量的获取,成员方法的获取,方法参数的获取以及通过反射机制对方法的使用,完整Demo见附件,正文只贴出主要代码,代码里面注释很多,就不再一一解释了。

package zh.Reflect;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;


public class TestReflect {
ArrayList<Method> methodList = new ArrayList<Method>();
HashMap<String, Method> methodMap = new HashMap<String, Method>();
public void reflectStudent()
{
try{
Class<?> Studentclass = Student.class;
System.out.println("Student所属于的类->"+Studentclass);
Student studentInstance = (Student) Studentclass.newInstance();
//构造函数
System.out.println("-------构造函数-------------------------------");
System.out.println(Studentclass.getConstructors());

//成员变量
System.out.println("-------成员变量--------------------------------");
Field[] fields = Studentclass.getDeclaredFields();
for (Field field:fields) {
String fieldName = field.getName();
System.out.println("fieldName->"+fieldName);

}
//获得类中的所有方法名
System.out.println("-------成员方法--------------------------------");
for (Method method : Studentclass.getMethods()) {
System.out.println("method->"+method.getName());
methodList.add(method);
methodMap.put(method.getName(), method);

}
//得到方法的参数
System.out.println("方法的参数-------------------------------------");
for (Method method : Studentclass.getMethods())
{
Type[] params = method.getGenericParameterTypes();
System.out.println(""+method.getName()+"->:");
for (Type param : params) {
System.out.println(param);
}
}
//得到方法的参数后就可以根据参数使用方法-使用List
System.out.println("-------使用方法--使用List存储------------------------------");
for (int i = 0; i < methodList.size(); i++) {
Method method = methodList.get(i);
if(method.getName().equals("setAge"))
{
method.invoke(studentInstance, "the age is from method invoke");
}
if (method.getName().equals("printStudentInfo")) 
{
method.invoke(studentInstance, null);
}
}
//得到方法的参数后就可以根据参数使用方法-使用List
System.out.println("-------使用方法--使用Map存储------------------------------");
methodMap.get("printStudentInfo").invoke(studentInstance, null);






}catch(Exception e)
{
e.printStackTrace();
}


}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值