Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use of "this" and "class" as members

Tags:

java

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.

like image 886
spot Avatar asked Dec 18 '22 03:12

spot


1 Answers

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.

like image 57
Tom Hawtin - tackline Avatar answered Dec 19 '22 16:12

Tom Hawtin - tackline