Java - 如何更改“本地"?事件侦听器中的变量

2022-01-15 00:00:00 variables event-handling java

有个小问题,希望有人能回答.基本上我有一个字符串变量,它需要根据组合框中的值进行更改,该组合框中附加了一个事件侦听器.但是,如果我将字符串设为 final,则无法更改,但如果我不将其设为 final,则 eclipse 会抱怨它不是最终的.最好(和最简单)的解决方法是什么?

Got a quick question which I hope someone can answer. Basically I have a String variable which needs changing based upon the value in a combo box which has an event listener attached to it. However if I make the string final then it cant be changed, but if i don't make it final then eclipse moans that it isn't final. Whats the best (and simplest) work around?

代码如下

final String dialogOutCome = "";

//create a listener for the combo box
Listener selection = new Listener() {

    public void handleEvent(Event event) {
    //get the value from the combo box
    String comboVal = combo.getText();

    switch (comboVal) {
         case "A": dialogOutCome = "a";
         case "B": dialogOutCome = "b";
         case "C": dialogOutCome = "c";
         case "D": dialogOutCome = "d";
    }
   }
};

推荐答案

你不能.

考虑一下:

  • 只要声明的方法运行,局部变量就存在.
  • 只要方法调用结束(通常是因为方法存在),变量就会消失
  • 听众可以(而且通常确实)活得更久

那么当方法已经返回并且监听器尝试修改局部变量时会发生什么?

So what should happen when the method returned already and the listener tries to modify the local variable?

因为这个问题没有很好的答案,他们决定通过不允许访问非final 局部变量来使这种情况变得不可能.

Because this question does not have a really good answer, they decided to make that scenario impossible by not allowing access to non-final local variables.

有两种方法可以解决这个问题:

There are two ways around this problem:

  • 尝试更改字段而不是局部变量(这可能也更适合监听器的生命周期)或
  • 使用 final 局部变量,您可以更改其中的 content(例如 ListString[] 使用单个元素).
  • try to change a field instead of a local variable (this probably also fits better with the life-time of the listener) or
  • use a final local variable, of which you can change the content (for example a List or a String[] with a single element).

相关文章