- import java.lang.reflect.Field;
- public class My
- {
- 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();
- 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;
- }
- }
复制代码 Field[] fields = bk1.getClass().getDeclaredFields(); 这个地方你用错方法了, 应该用这一个 。 多查api文档 ,
下面是不是你要的结果 .
Book:name=jlvl progrlm,
color=yellow,
chubanshe=qing hul dl xue chu bln she,
page=345
替换掉其中的a。
|