空闻大师 2014-09-04 01:16 采纳率: 50%
浏览 8933
已采纳

java方面:private属性,没有set方法,只有get方法,如何给这个属性赋值?

如题;

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赋值,怎么办?

  • 写回答

8条回答

  • three_man 2014-10-21 04:39
    关注

    用反射吧,然后设置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());
    }
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊