/**
*
*/
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import p2.User;
@SuppressWarnings("unchecked")
public class TestReflection02 {
public static void main(String[] a) throws Exception{
User p1 = new User("张三",18);
TestReflection02 t = new TestReflection02();
System.out.println("----------------------------------------");
t.mf1(p1,"name","李四");
t.mf1(p1,"age",30);
System.out.println(p1);
System.out.println("----------------------------------------");
t.mf2("p2.User", "total",88);
System.out.println("----------------------------------------");
Class[] argTypes = {String.class,int.class};
Object[] args = new Object[]{"王五",99};
t.mf3(p1, "setAll",argTypes,args);
System.out.println(p1);
System.out.println("----------------------------------------");
t.mf4("p2.User", "showTotal",null,null);
}
//直接操作对象属性
public void mf1(Object o,String fieldName,Object newValue) throws NoSuchFieldException, IllegalAccessException {
Class c = o.getClass();
Field f = c.getField(fieldName);
Object fv = f.get(o);
System.out.print("修改前:" + fieldName + "=" + fv);
f.set(o,newValue);
System.out.println("/t修改后:" + fieldName + "=" + f.get(o));
}
//直接操作类属性
public void mf2(String className,String fieldName,Object newValue) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
Class c = Class.forName(className);
Field f = c.getField(fieldName);
Object fv = f.get(c);
System.out.print("修改前:" + fieldName + "=" + fv);
f.set(c,newValue);
System.out.println("/t修改后:" + fieldName + "=" + f.get(c));
}
//调用对象成员方法
public void mf3(Object o,String methodName,Class[]argTypes,Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
Class c = o.getClass();
Method m = c.getMethod(methodName, argTypes);
Object result = m.invoke(o, args);
System.out.println(result);
}
//调用类成员方法
public void mf4(String className,String methodName,Class[]argTypes,Object[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class c = Class.forName(className);
Method m = c.getMethod(methodName, argTypes);
Object result = m.invoke(null, args);
System.out.println("result:" + result);
}
}