开发者

Access the outer class instance within the anonymous inner class in Java [duplicate]

开发者 https://www.devze.com 2023-03-17 04:57 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: keyword for the outer class from an anonymous inner class?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

keyword for the outer class from an anonymous inner class?

I need to access the instance of the outer class within the anonymous inner class and did something like this. Can anyone clarify whether this is correct or not?

public class ClassA{

ClassA refernceOfClassA = this;  

    public void m(){
       //Do something
    }
    Runnable target = new Runna开发者_开发知识库ble(){
       public void run(){
           //Code goes here using the refernceOfClassA
           refernceOfClassA.m();      
       }
    };
}


You should be able to just call the method m() from the inner class.

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


I do not believe you even need the referenceOfClassA. You can just access properties on the outer class and call its methods normally.

0

精彩评论

暂无评论...
验证码 换一张
取 消