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.
ClassName.this
is used to reference the current instance of an outerclass from an inner class.Usually, you can use only
this
. But, sometimesthis
makes reference to an inner class... so, for example:One at a time:
The first construct is called a qualified this. The purpose of the syntax is in the case where you are in an inner class (typically an anonymous inner class) and you want to reference the
this
of the outer class rather than thethis
of the (anonymous) inner class. The "qualified this" can only be used in a context wherethis
would be ambiguous. The quote the JLS "It is a compile-time error if the expression occurs in a class or interface which is not an inner class of class T or T itself".The second construct is called a
class literal
is the way to reference the Class object that represents that type. It can be used in any context.is used in nested classes to refer to the current instance of the enclosing class, since the `this' keyword refers to the nest class instance.
The syntax "Classname.this" is for inner classes. If you want to refer to the enclosing instance of type "Outerclass" then you do it as "Outerclass.this".
NextActivity.class is simply the Class object that describes class "NextActivity".
NextActivity.class
in java meanstypeof(NextActivity)
in C#