反射--操作

 

/**
*
*/
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);
}  
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值