如何从匿名类中访问封闭的类实例变量?

时间:2013-04-05 01:44:36

标签: java anonymous-class anonymous-inner-class

如何从匿名类的方法中访问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();
   }
}

3 个答案:

答案 0 :(得分: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,这是选民显然没有阅读的内容。并没有阅读理解代码。

答案 1 :(得分: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();
   }  }

答案 2 :(得分: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() {
            System.out.println("Button's text is: " + button.getText());
         }
      };
      new Thread(r).start();
   }
}

更重要的是:为什么这不适合你?