A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 孙国军 中级黑马   /  2012-5-1 00:48  /  1799 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.lang.reflect.Field;

  2. class ReflectTest
  3. {
  4. public static void main(String[] args){
  5. ReflectPoint rp=new ReflectPoint(3,8);
  6. changeStringValue(rp);
  7. System.out.println(rp);
  8. }
  9. private static void changeStringValue(Object obj) {

  10. Field[] field=obj.getClass().getFields();
  11. for(Field f:field){
  12. if(f.getType()==String.class){ //因为返回的是同一个Class对象,所以使用"=="判断;
  13. try {
  14. String oldStr=(String)f.get(obj);
  15. String newStr=oldStr.replace('b', 'a');
  16. f.set(obj, newStr);
  17. } catch (IllegalArgumentException e) {

  18. e.printStackTrace();
  19. } catch (IllegalAccessException e) {

  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. }
  25. }
  26. class ReflectPoint {
  27. private int x;
  28. public int y;
  29. public String str1="search";
  30. public String str2="java";
  31. public String str3="enum";
  32. public ReflectPoint(int x, int y) {
  33. super();
  34. this.x = x;
  35. this.y = y;
  36. }
  37. public String toString() {
  38. return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="
  39. + str3 + "]";
  40. }

  41. }
复制代码


为什么,对象rp中的String类型的属性值没有改变啊??

3 个回复

倒序浏览
17行,a换b还是b换a?
回复 使用道具 举报
String replace(char oldChar, char newChar)
          返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

你的字符位置放错了,如果想换掉所有'a'的话,a字符应该在前面。其他的看下来,貌似都木有错误= =
回复 使用道具 举报
01.import java.lang.reflect.Field;

02.

03.class ReflectTest

04.{

05.public static void main(String[] args){

06.ReflectPoint rp=new ReflectPoint(3,8);

07.changeStringValue(rp);

08.System.out.println(rp);

09.}

10.private static void changeStringValue(Object obj) {

11.

12.Field[] field=obj.getClass().getFields();

13.for(Field f:field){

14.if(f.getType()==String.class){ //因为返回的是同一个Class对象,所以使用"=="判断;

15.try {

16.String oldStr=(String)f.get(obj);

17.String newStr=oldStr.replace('b', 'a');//你在这儿是把b换成a,但是你写String中的字符串一个包含b的都没有,所以没找要替换的目标当然就不变了。

18.f.set(obj, newStr);

19.} catch (IllegalArgumentException e) {

20.

21.e.printStackTrace();

22.} catch (IllegalAccessException e) {

23.

24.e.printStackTrace();

25.}

26.}

27.}

28.}

29.}

30.class ReflectPoint {

31.private int x;

32.public int y;

33.public String str1="search";

34.public String str2="java";

35.public String str3="enum";

36.public ReflectPoint(int x, int y) {

37.super();

38.this.x = x;

39.this.y = y;

40.}

41.public String toString() {

42.return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="

43.+ str3 + "]";

44.}

45.

46.}

评分

参与人数 1黑马币 +3 收起 理由
孙国军 + 3 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马