你好,
我有以下代码,我想要的是将名为 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 启动之前无法更改所述变量的值?
慕尼黑的夜晚无繁华
沧海一幻觉
相关分类