繁体   English   中英

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

[英]Change value in private member in JFrame with reflection

你好,

我有以下代码,我想要的是将名为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启动之前更改所述变量的值?

更新这是我想要的,在JFrame启动之前修改值,但要进行反射

final Field field = Class.forName(C).getDeclaredField("jLabel");
field.setAccessible(true);
if(field.getType() == JLabel.class) {
  final JLabel j = (JLabel)field.get(ReflectionOnClass.class.newInstance());
  j.setText("X: " + 5000);
}

在此处输入图片说明

这是可能的。 您可以将此函数添加到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());

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM