import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ReflectTest {
public int age = 2012;
public String name = "世界末日";
public int add(int param1, int param2) {
return param1 + param2;
}
public String show(String mesg) {
return "show" + mesg;
}
public static void main(String[] args) throws Exception {
Class<?> classType = ReflectTest.class;
Object invokeMethod = classType.newInstance();
Field[] fields = classType.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
System.out.println(Modifier.toString(mod) // 取得修饰符
+ " " + field.getType().getName() // 取得类型名
+ " " + field.getName() // 取得属性名
+ " "+ field.get(invokeMethod)); //取得属性值
}
Method addMethod = classType.getMethod("add", new Class[] { int.class,int.class });
//Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,
/**
* @param 方法所在的实体类
* @param 方法所需参数
*/
Object result = addMethod.invoke(invokeMethod, new Object[] {new Integer(100), new Integer(200) });
System.out.println(result);
Method echoMethod = classType.getMethod("show",new Class[] { String.class });
result = echoMethod.invoke(invokeMethod, new Object[] { "hello" });
System.out.println(result);
}
}