JAVA 在对象名称中使用变量

JAVA use variable in object name

这是我的一些代码 class:

public class update implements ItemListener {

private String TBL;

public void init(String pav, String type) { 
    try {
        this.TBL = type;
        Connection conn = sqlite.ConnectDb();
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("SELECT * FROM "+TBL+"_imones order by pav asc;");

        pard_reg_imone_choice.removeAll();
        pard_imone_choice.removeAll();

        pard_reg_imone_choice.addItem("VISOS");

        while (rs.next()) {
            pard_reg_imone_choice.addItem(rs.getString("pav"));
            pard_imone_choice.addItem(rs.getString("pav"));
        }

        pard_imone_choice.addItemListener(this);

        rs.close();

我需要这样的东西:

{variable}_reg_imone_choice.removeAll();
{variable}_imone_choice.removeAll();

变量为字符串类型(即"pirk"和"pard")。

谢谢!

如果情况不多,可以使用 switch 语句

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

除了 map 方法之外,其他人建议我能想到的唯一机制是反射

Field field = this.getClass().getField(name+"_reg_imone_choice");
Object object = field.get (this);
((List) object).removeAll ();

您不能将字符串插入 Java 中的变量名。不是在运行时。不是在编译时。 Java变量名必须在编译时完整拼写。

您在 Java 中最接近的方法是使用 Map<String, Choice> ... 像这样的东西:

  Map<String, Choice> choices = ... // initialize
  ....
  String prefix = ...
  ....
  choices.get(prefix + "_reg_imone_choice").removeAll();
  choices.get(prefix + "_imone_choice").removeAll();

也可以使用反射来做到这一点,前提是变量是静态或实例字段。 (反射不能用于访问局部变量或方法参数。)


但是,这些解决方案对于有经验的 Java 程序员来说是背道而驰的,因为您在代码库中引入了各种运行时检查......以及各种不必要的 (IMO) 脆弱性。

当您开始以 Java 方式思考问题时,通常 有更好的方法来完成这种事情。