本帖最后由 Inspur 于 2013-9-20 10:50 编辑
/*
将任意一个对象中的String类型的变量所对应的字符串内容中的b改为a
*/
import java.lang.reflect.*;
class ReflectDemo
{
public static void main(String[] args) throws Exception
{
Printed obj = new Printed();
ojbectChanged(obj);
System.out.println(obj.toString());
}
public static void ojbectChanged(Object obj) throws Exception
{
Field[] Fields = obj.getClass().getFields();
for(Field field:Fields)
{
if(field.getType() == String.class)
{
String oldValueString = (String)field.get(obj);
System.out.println(oldValueString);
String newValueString = oldValueString.replace('b', 'a');
System.out.println(newValueString);
field.set(obj, newValueString);
}
}
}
}
class Printed
{
String a = "ball";
String b = "basketball";
public String toString()
{
return a+" "+b;
}
}
运行没有出现想要的结果,请高手解决,谢谢
|