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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yp324 中级黑马   /  2013-6-3 15:43  /  1092 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 yp324 于 2013-6-3 22:28 编辑

import java.lang.reflect.*;
public class ReflectTest {
        public static void main(String[] args) throws Exception{        
                Book bk1 = new Book("java program","yellow","qing hua da xue chu ban she",345);
                Field[] fields = bk1.getClass().getFields();
                for(Field field:fields){
                        if(field.getType() == String.class){
                                String oldValue = (String)field.get(bk1);
                                String newValue = oldValue.replace('a', 'l');
                                field.set(bk1,newValue);
                        }
                }
                System.out.println(bk1);
        }        
}
class Book {
        String name;
        String color ;
        String chubanshe ;
        int page;
        Book(String name, String color, String chubanshe,int page) {
               
                this.name = name;
                this.color = color;
                this.chubanshe = chubanshe;
                this.page = page;
        }
        public String toString() {
                return "Book:name=" + name + ",\r\ncolor=" + color + ", \r\nchubanshe="
                                + chubanshe + ",\r\npage="+page;
        }
}上面这段代码修改字符串没有成功?

评分

参与人数 1技术分 +1 收起 理由
曹睿翔 + 1 神马都是浮云

查看全部评分

2 个回复

倒序浏览
getDeclaredFields()代替你程序里的getFields()方法即可
public class ReflectTest {
        public static void main(String[] args) throws Exception{        
                Book bk1 = new Book("java program","yellow","qing hua da xue chu ban she",345);
                Field[] fields = bk1.getClass().getDeclaredFields();//这里你用的方法只能获取public修饰的属性,用这个能获取所有的
              
                for(Field field:fields){
                       
                        if(field.getType() == String.class){
                               
                                String oldValue = (String)field.get(bk1);
                                String newValue = oldValue.replace('a', 'l');
                                field.set(bk1,newValue);
                        }
                }
                System.out.println(bk1);
        }        
}
class Book {
        String name;
        String color ;
        String chubanshe ;
        int page;
        Book(String name, String color, String chubanshe,int page) {
               
                this.name = name;
                this.color = color;
                this.chubanshe = chubanshe;
                this.page = page;
        }
        public String toString() {
                return "Book:name=" + name + ",\r\ncolor=" + color + ", \r\nchubanshe="
                                + chubanshe + ",\r\npage="+page;
        }
}
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马