猿问

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

你好,


我有以下代码,我想要的是将名为 number 的实例的值修改为任何值


我在同一个包中有两个类


ReflectionOnClass.class


import 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.class


import 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 启动之前无法更改所述变量的值?



ITMISS
浏览 152回答 2
2回答

慕尼黑的夜晚无繁华

这是可能的。您可以将此函数添加到 ReflectionOnClass:public void setNumber(int num){&nbsp; &nbsp; this.number = num;&nbsp; &nbsp; label.setText("X: " + this.number);}public int getNumber(){&nbsp; &nbsp; return this.number;}并从 ExecReflection 调用它们:final ReflectionOnClass rF = new ReflectionOnClass();rF.setNumber(4);System.out.println("Value number: " + rF.getNumber());

沧海一幻觉

没有任何变化,因为您实际上并未更改显示的值private int number = 2;private JLabel jLabel = new JLabel("X: " + number);您需要访问jLabel字段,因为这是您显示的值,并将文本更改为其他内容,如果number在其他地方使用,那么您可能需要更改它们,因此number对于此示例 100 值,并将jLabel文本更改为X: 100
随时随地看视频慕课网APP

相关分类

Java
我要回答