Using “this” with class name

2019-01-08 03:58发布

I am doing Android programming and was learning about Intents, when I saw a constructor that, to my C# trained mind, seemed funky. The call was:

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

Both of the parameters are new to me. How is there a static ".this" off of a Class Name? Is this a Java thing or an Android thing? I am assuming that it is the same as just saying "this", since I am in the context of CurrentActivity, but I don't get how the "this" can be called off of the Class name itself. Also. The ".class" looks like it is used for reflection, which I am familiar with in C#, but any insight into this would be welcomed as well.

Thanks.

7条回答
在下西门庆
2楼-- · 2019-01-08 05:01

It's confusing only because when you use "MainActivity.this", it seems that you are referring to the class and not the object. In reality when you use "this" you are always referring to the current object, as the java se documentation states:

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

It's just syntactically peculiar.

查看更多
登录 后发表回答