- import java.lang.reflect.Field;
- class ReflectTest
- {
- public static void main(String[] args){
- ReflectPoint rp=new ReflectPoint(3,8);
- changeStringValue(rp);
- System.out.println(rp);
- }
- private static void changeStringValue(Object obj) {
- Field[] field=obj.getClass().getFields();
- for(Field f:field){
- if(f.getType()==String.class){ //因为返回的是同一个Class对象,所以使用"=="判断;
- try {
- String oldStr=(String)f.get(obj);
- String newStr=oldStr.replace('b', 'a');
- f.set(obj, newStr);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
- class ReflectPoint {
- private int x;
- public int y;
- public String str1="search";
- public String str2="java";
- public String str3="enum";
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
- public String toString() {
- return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
- + str3 + "]";
- }
- }
复制代码
为什么,对象rp中的String类型的属性值没有改变啊??
|
|