java反射 遍历字段
import java.lang.reflect.Field;
/**
* Created by 89742 on 7/19/2015.
*/
public class ReflectTest {
public static void main(String[] args) throws Exception {
ReflectPoint rp = new ReflectPoint();
changeStringValue(rp);
System.out.println(rp);
}
public static void changeStringValue(Object obj) throws Exception {
Field[] fields = obj.getClass().getFields();
for (Field field : fields) {
System.out.print(field.getName());
if (field.getType() == String.class) {
String oldValue = (String) field.get(obj);
String newValue = oldValue.replace("tangxin", "Michael");
field.set(obj, newValue);
}
}
}
}
/**
* Created by 89742 on 7/18/2015.
*/
public class ReflectPoint {
public String str1 = "tangxin.club";
public String str2 = "tangxin.club";
public String str3 = "tangxin.club";
@Override
public String toString() {
return "ReflectPoint{" +
"str1='" + str1 + '\'' +
", str2='" + str2 + '\'' +
", str3='" + str3 + '\'' +
'}';
}
}