今天看了张老师的反射视频,但是自己动手做的时候总是取不到局部变量,请高手看一下错在哪里?
public class Test2 { public int a ; public int b; String s1 = "basketball"; String s2 = "ball"; public Test2(int a , int b) { this.a = a; this.b = b; } public String toString() { return s1 +";"+ s2; }
} package com.jianjian; import java.lang.reflect.Field; public class Test3 { public static void main(String[] args) throws Exception { Test2 test = new Test2(3,5); Class c = test .getClass(); //首先筛出所有的成员变量 Field[] f = c.getFields(); for(Field field : f) { if(field.getType() == String.class) { String str = (String)field.get(test); String newStr = str.replace('b','a'); System.out.println(newStr); field.set(test,newStr); } } System.out.println(test); } } |