如题;
public class Foo {
private String readwrite; // with getter and setter
private String readonly; // with getter
public String getReadwrite() {
return readwrite;
}
public void setReadwrite(String readwrite) {
this.readwrite = readwrite;
}
public String getReadonly() {
return readonly;
}
}
当我在其他类中调用Foo时,想给其readonly赋值,怎么办?
用反射吧,然后设置setAccessible为true就可以了,如下:
public class Test {
private String readOnly;
public String getReadOnly() {
return readOnly;
}
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Test t = new Test();
Field f = t.getClass().getDeclaredField("readOnly");
f.setAccessible(true);
f.set(t, "test");
System.out.println(t.getReadOnly());
}
}
你这么设计不觉得矛盾么,既然不给set方法,那就是只读的,在foo里就直接赋值。
你又要在别的类中去赋值,那干嘛不给set方法。
foo.readonly="";
1.同意楼上的看法,最好是给readonly加一个set方法。如下
public void setReadonly(String readonly) {
this.readonly= readonly;
}
2.你可以写一个别的方法来设置readonly的值(呵呵,还不如给它加set方法)如下:
public void xxxx(String readonly){
this.readonly = readonly;
}
在构造方法里赋值
//构造方法
public Foo(String readonly){
this.readonly = readonly;
}
//调用
new Foo("readonly");
扩展包JODD可以,不对Foo进行任何修改
我觉得这应该是去面试时,人家提出的问题。写一个构成(constructor)的办法是对的。
应该是面试时候问的吧用一个有参数的构造方法赋值就可以了不会连构造方法也不让用吧!
面试问这些稀奇古怪的题其实基本上就是想用你了就是想压你的工资你自己往下降个1000,700的基本上就没问题了
反射可以实现
关键是在获得的字段上setAccessible=true