本帖最后由 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;
}
}上面这段代码修改字符串没有成功?
|