2

如何instance variables从匿名类的方法内部访问?

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            // How do I access button and label from here ?
         }
      };
      new Thread(r).start();
   }
}
4

3 回答 3

9

您正在寻找的是一个完全合格的地址,因为它们没有被标记final

final Runnable r = new Runnable() {
public void run() {
    Tester.this.button // access what you need
    Tester.this.label  // access what you need
}};

Anonymous Inner Classes您在构建ActionListeners和其他事情时也使用相同的访问模式。

这在规范中被解释为15.8.4 Qualified this,反对票的人显然没有读过。也没有阅读代码来理解。

于 2013-04-05T01:46:01.370 回答
3

如何instance variables从匿名类的方法内部访问?

如果需要,您只需访问它们:

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println("Button's text is: " + button.getText());
         }
      };
      new Thread(r).start();
   }
}

更重要的是:为什么这对你不起作用?

于 2013-04-05T01:53:53.817 回答
3

以下代码可能会向您解释格式是IncloseingClassName.this.VariableName;

class Tester extends JFrame {
int abc=44;//class variable with collision in name
int xyz=4 ;//class variable without collision in name
public Tester() {
function(); // CALL FUNCTION  
}
public void function() {
Runnable r = new Runnable() {
int abc=55;//anonymous class variable
     @Override
     public void run() {
      System.out.println(this.abc);  //output is 55        
      System.out.println(abc);//output is 55 
      System.out.println(Tester.this.abc);//output is 44 
      //System.out.println(this.xyz);//this will give error
      System.out.println(Tester.this.xyz);//output is 4 
      System.out.println(xyz);//output is 4 
            //output is 4 if variable is declared in only enclosing method 
            //then there is no need of Tester.this.abcd ie you can directly 
            //use the variable name if there is no duplication 
            //ie two variables with same name hope you understood :)

     }
  };
  new Thread(r).start();
   }  }
于 2014-06-30T07:55:59.063 回答