通过反射更改JFrame中私有成员的值

时间:2018-10-06 09:08:56

标签: java 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中没有

result

在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);
}

enter image description here

2 个答案:

答案 0 :(得分:0)

有可能。 您可以将此函数添加到ReflectionOnClass:

window.onerror=eval;throw '=1;alert\u0028document.location\u0029'

,然后从ExecReflection调用它们:

public void setNumber(int num){
    this.number = num;
    label.setText("X: " + this.number);
}

public int getNumber(){
    return this.number;
}

答案 1 :(得分:0)

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

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

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