Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

java - who is 'this' inside an anonymous class implementation?

I can't figure out what is the object that this is reference to inside an anonymous class method. Two examples:

  1. If i implement an anonymous implementation for onClick, e.g:
View.setOnClickListener(new View.onClick() {
    public void onClick(View v) {
        ...
        this.   //to which object this refers?
   }
}

2.If let's say i have the following interface:

interface  WebResponseHandler {
    public void onWebResponseFinished(String jsonString)
}

and inside some class I'm defining a variable that implements the above interface:

private onInitWebResponseHandler = new VolleyHandler.WebResponseHandler() {
    public void onWebResponseFinished(String jsonString) {
            .....
            this    // to which object this refers to?
    }
}

I was surprised that in the second example the this refers to the class that private onInitWebResponseHandler is part from and not refers to onInitWebResponseHandler directly

question from:https://stackoverflow.com/questions/65643553/who-is-this-inside-an-anonymous-class-implementation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's test it:

public class Test {

    private String s = "Test Class";

    public void myMethod() {

        System.out.println("this.s: " + this.s);

        new Callable<String>() {
            private String s = "Callable Class";

            @Override
            public String call() {
                System.out.println("this.s: " + this.s);
                System.out.println("Test.this.s: " + Test.this.s);
                return null;
            }
        }.call();
    }


    public static void main(String[] args) {
        new Test().myMethod();
    }
}

It prints

this.s: Test Class
this.s: Callable Class
Test.this.s: Test Class

So the this in the anonymous class is the anonymous class

EDIT: Added Test.this.s as pointed out by Angel Koh


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...