import java.lang.reflect.Field;
public class ReflectTest {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
StringDemo str = new StringDemo(1);
Field fieldx = str.getClass().getDeclaredField("num");
fieldx.setAccessible(true);
System.out.println(fieldx.get(str));
changeStringValue(str);
System.out.println(str);
}
private static void changeStringValue(Object obj) throws Exception
{
Field[] fields = obj.getClass().getDeclaredFields();
for(Field field:fields)
{
field.setAccessible(true);
if(field.getType() == String.class)
{
String oldValue = (String) field.get(obj);
String newValue = (String) oldValue.replace('a', 'b');
field.set(obj,newValue);
}
}
}
}
class StringDemo {
private String str1 = "apple";
private String str2 = "banana";
private String str3 = "watermelon";
private int num;
StringDemo(int x){
this.num = x;
}
public String toString()
{
return str1+":"+str2+":"+str3;
}
}
利用成员变量反射,把StringDemo里字符串中a换成b...
如果StringDemo里的成员变量都是private权限的,那该怎么做呢?
我本来是想用static void [url=mk:@MSITStore:E:\java%20date\Java_JDK_API%201.6.0(6.0)_CN.CHM::/java/lang/reflect/AccessibleObject.html#setAccessible(java.lang.reflect.AccessibleObject[], boolean)]setAccessible[/url](AccessibleObject[] array, boolean flag)这一方法来强制更改的,但是不知道怎么用
于是用void setAccessible(boolean flag)这个方法来实现,感觉有点不爽
不知道哪位大神有更牛的方法。。。
|
|