黑马程序员技术交流社区

标题: 超经典的反射,给大家分享一下,绝对经典, [打印本页]

作者: 草上飞    时间: 2012-11-11 22:22
标题: 超经典的反射,给大家分享一下,绝对经典,
package com.csdn.day1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ReflectTest {
/**
  * @param args
  */
public static void main(String[] args) throws Exception{
  
  ReflectPrint rp=new ReflectPrint(3,6);//这个类见下面
  Field fx=rp.getClass().getDeclaredField("x");
  fx.setAccessible(true);//设置强制使用这个反射,因为这是私有的
  Field fy=rp.getClass().getField("y");
//  System.out.println(fx.get(rp));
//  System.out.println(fy.get(rp));
//  
  
  changeStringValues(rp);//创建一个方法,通过反射改变rp中的值
  System.out.println(rp);
  
}
private static void changeStringValues(Object obj) throws Exception {
  Field[] fields=obj.getClass().getFields();//通过obj对象的字节码,获取所有的字段
  for (Field fiel : fields) {
   //这就最好用==因为这两个对象都是字符串,可以比较
   if(fiel.getType()==String.class)//判断获取的String.class类型是否相等//String.class这是表示只获取string对象的字节码
   {
   String str=(String) fiel.get(obj);//将或取得对象转换成string类型  
       str=str.replace('b', '8');
       fiel.set(obj,str);
   }
   
  }
  
   
  
  
}
}


===========================================
package com.csdn.day1;
public class ReflectPrint {
private int x;
public int y;
public String str1="ball";
public String str2="basketball";
public String str3="heima";
public ReflectPrint(int x, int y) {
  super();
  this.x = x;
  this.y = y;
}
@Override
public String toString()
{  
  return str1+"---"+str2+"----"+str3;
  
}
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2