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();
}
}
}