【问题标题】:Access the outer class instance within the anonymous inner class in Java [duplicate]在Java中访问匿名内部类中的外部类实例[重复]
【发布时间】:2011-07-03 19:16:50
【问题描述】:

可能重复:
keyword for the outer class from an anonymous inner class?

我需要在匿名内部类中访问外部类的实例并执行类似的操作。谁能澄清这是否正确?

public class ClassA{

ClassA refernceOfClassA = this;  

    public void m(){
       //Do something
    }
    Runnable target = new Runnable(){
       public void run(){
           //Code goes here using the refernceOfClassA
           refernceOfClassA.m();      
       }
    };
}

【问题讨论】:

    标签: java anonymous-inner-class


    【解决方案1】:

    您应该可以只从内部类调用方法m()

    public class ClassA{    
        public void m(){
           //Do something
        }
        Runnable target = new Runnable(){
           public void run(){
               //Code goes here using the refernceOfClassA
               m();      
           }
        };
    }
    

    【讨论】:

      【解决方案2】:

      我认为您甚至不需要referenceOfClassA。您可以只访问外部类的属性并正常调用其方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-21
        • 1970-01-01
        相关资源
        最近更新 更多