为了账号安全,请及时绑定邮箱和手机立即绑定

使用反射更改 JFrame 中私有成员的值

使用反射更改 JFrame 中私有成员的值

ITMISS 2021-10-28 17:19:08
你好,我有以下代码,我想要的是将名为 number 的实例的值修改为任何值我在同一个包中有两个类ReflectionOnClass.classimport javax.swing.*;import java.awt.*;public class ReflectionOnClass extends JFrame {private int number = 2;private JLabel jLabel = new JLabel("X: " + number);public ReflectionOnClass() {    setLayout(new FlowLayout());    setPreferredSize(new Dimension(200,200));    add(jLabel);    setDefaultCloseOperation(3);    setLocationRelativeTo(null);    pack();    setVisible(true);    }}ExecReflection.classimport java.lang.reflect.Field;import java.util.stream.Stream;public class ExecReflection {private static final String C = "ReflectionOnClass";public ExecReflection() {    try {        final Field field = Class.forName(C).getDeclaredField("number");        field.setAccessible(true);        final ReflectionOnClass rF = new ReflectionOnClass();        field.set(rF , 100);        mostrar("Value number: " + field.get(rF));    }catch (Exception ex){        ex.printStackTrace();    } } public <T> void mostrar(final T t){System.out.println(t);} public static void main(String ...gaga) {    final Runnable r = ExecReflection::new;    r.run(); }}输出与图像中的一样正确,但在 JFrame 中没有在 JFrame 启动之前无法更改所述变量的值?
查看完整描述

2 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

这是可能的。您可以将此函数添加到 ReflectionOnClass:


public void setNumber(int num){

    this.number = num;

    label.setText("X: " + this.number);

}


public int getNumber(){

    return this.number;

}

并从 ExecReflection 调用它们:


final ReflectionOnClass rF = new ReflectionOnClass();

rF.setNumber(4);

System.out.println("Value number: " + rF.getNumber());


查看完整回答
反对 回复 2021-10-28
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

没有任何变化,因为您实际上并未更改显示的值


private int number = 2;

private JLabel jLabel = new JLabel("X: " + number);

您需要访问jLabel字段,因为这是您显示的值,并将文本更改为其他内容,如果number在其他地方使用,那么您可能需要更改它们,因此number对于此示例 100 值,并将jLabel文本更改为X: 100


查看完整回答
反对 回复 2021-10-28
  • 2 回答
  • 0 关注
  • 151 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信