本帖最后由 清心玉质 于 2013-8-5 20:58 编辑
- <DIV class=blockcode>
- <BLOCKQUOTE>package frogbean;
- public class ReflectionPoint {
- private int x;
- public int y;
- public String str1 = "ball";
- public String str2= "basketball";
- public String str3 = "itcast";
- public ReflectionPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- public String toString(){
- return str1 +":"+str2+":"+str3;
- }
- }
复制代码
package frogbean;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import org.omg.CORBA.Object;
public class ReflectionTest {
public static void main(String args[])throws Exception
{
ReflectionPoint pt1 = new ReflectionPoint(3,5);
Field fieldY = pt1.getClass().getField("y");
//fieldY的值是多少?5?错
//fieldY不是对象身上的变量,而是类上的,要用它去取某个对象上的值代表类字节码的变量,没对应到对象的身上的值
System.out.println(fieldY.get(pt1));
Field fieldX = pt1.getClass().getDeclaredField("x");//getField("x")不能拿到私有成员
fieldX.setAccessible(true);//暴力反射,强制获取私有变量值
System.out.println(fieldX.get(pt1));
changeStringValue(pt1);//错误出现在这行
System.out.println(pt1);
}
private static void changeStringValue(Object obj)throws Exception{
// TODO Auto-generated method stub
Field[] fields = obj.getClass().getFields();
for(Field field : fields){
if(field.getType() == String.class){
String oldValue = (String)field.get(obj);
String newValue = oldValue.replace('b','a');
field.set(obj, newValue);
}
}
}
}
|