更改ReflecStr类的对象rs中的成员变量str1和str2所对应的字符串内容,
把'a'改成'z',把'z'改成'a',此例很好的演示了反射的作用。
程序如下:
import java.lang.reflect.Field;
public class ReflectStr
{
public static String str1;
public static String str2;
public ReflectStr(String str1, String str2)
{
super();
this.str1 = str1;
this.str2 = str2;
}
private static void changeStringValue(Object obj) throws Exception
{
Field fields[]=obj.getClass().getFields();
for(Field field : fields)
{
if(field.getType() == String.class)
{
String oldvalue=(String)field.get(obj);
String newvalue="";
if(oldvalue.contains("a")&&oldvalue.contains("z"))
{
for(int i=0;i<oldvalue.length();i++)
{
if(oldvalue.charAt(i)=='a')
newvalue+="z";
else if(oldvalue.charAt(i)=='z')
newvalue+="a";
else
newvalue+=(""+oldvalue.charAt(i));
}
}
else if(oldvalue.contains("a"))
newvalue=oldvalue.replace('a', 'z');
else if(oldvalue.contains("z"))
newvalue=oldvalue.replace('z', 'a');
field.set(obj, newvalue);
}
}
}
public String toString()
{
return "str1="+str1+",str2="+str2;
}
public static void main(String args[]) throws Exception
{
ReflectStr rs=new ReflectStr("abcxyz","aazzaa");
System.out.println(rs);
changeStringValue(rs);
System.out.println("改变值后: ");
System.out.println(rs);
}
}
程序运行结果
str1=abcxyz,str2=aazzaa
改变值后:
str1=zbcxya,str2=zzaazz