I have seen Java code that says something like:
SomeClass.this.someMethod(someArg);
Blah(AnotherClass.class);
Blah(YAClass.this);
What do "this" and "class" mean here? I am used to them as keywords to refer to the current object and to define a class, but this is different. My Java book and online searches have not yielded any explanation.
SomeClass.this
/YAClass.this
- the this
reference of an inner class' enclosing SomeClass
/YAClass
class.
class SomeClass {
private InnerClass {
public void foo() {
SomeClass outerThis = SomeClass.this;
[...]
}
}
}
(You need to be very careful which this
you get particularly when dealing with operations that could be applied to any Object
reference. A common case is syncronising on this
in an inner class, when the code should be synchronising on the outer instance (a better approach in this case is to use an explicit lock object).)
AnotherClass.class
- the java.lang.Class
object for the AnotherClass
class. Prior to Java 1.5 this was implemented using Class.forName
(initialising the class); from 1.5 the ldc
bytecode has been extended for direct support.
Class<AnotherClass> clazz = AnotherClass.class;
Both were introduced in Java 1.1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With