本帖最后由 ying 于 2013-1-8 00:32 编辑
- <P>package Test;
- import java.lang.reflect.Field;
- //利用反射把字符串中的a替换成b
- public class FrflectFieldDemo {</P>
- <P> public static void main(String[] args) throws Exception {
-
- ReflectTest rt = new ReflectTest();
- Field[] fields = rt.getClass().getFields();</P>
- <P> for (Field field : fields) {
- if (field.getType() == String.class) {
- String oldStr = (String) field.get(rt);
- String newSctr = oldStr.replace('a', 'b');
- System.out.println(newSctr);
- }
- }
- System.out.println("==========================================");
- //获取对象
- ReflectTest t = new ReflectTest();
-
- change(t);
- }
- public static void change(Object obj) throws Exception
- {
- //获取要操作的类的Class对象
- Class<?> classType = obj.getClass();
-
- //获取对象中的多有成员变量
- Field[] fields = classType.getFields();
-
- //操作成员变量
- for (int i = 0; i < fields.length; i++) {
- //获取第i个成员变量对象
- Field field = classType.getDeclaredField(fields[i].getName());
- //获取对象对应的值
- String fieldValue = field.get(obj).toString();
-
- System.out.println("oldFiledValue: " + fieldValue);
- //压制JVM对字段修饰符的检查
- field.setAccessible(false);
- //替换字段中的“a”为“b”
- String changeValue = fieldValue.replace("a", "b");
-
- System.out.println("newFieldValue: " + changeValue);
- }
- }
- }</P>
- <P>class ReflectTest {
- public String str1 = "football";
- public String str2 = "pingpangball";
- public String str3 = "haha";</P>
- <P> public ReflectTest() {
- }</P>
- <P> public String toString() {
- return str1 + ":" + str2 + ":" + str2;
- }
- }</P>
复制代码 你只是获取字段对象的值并做替换,你并没有把替换的结果重新赋值给对象
|