黑马程序员技术交流社区
标题:
反射的问题
[打印本页]
作者:
yp324
时间:
2013-6-3 15:43
标题:
反射的问题
本帖最后由 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;
}
}上面这段代码修改字符串没有成功?
作者:
tshch1989
时间:
2013-6-3 16:19
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;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2