簡體   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