spot
spot

Reputation: 108

use of "this" and "class" as members

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.

Upvotes: 4

Views: 202

Answers (4)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 7

YuppieNetworking
YuppieNetworking

Reputation: 8851

A quick example for inner class, to complete the other answers:

class SomeClass {
     public void someMethod() {
          System.out.println("Hello, I have someMethod");
     }
     public void otherMethod() {
          addListener(new MyListener() {
              public void someMethod () {
                  System.out.println("I too, have someMethod");
              }
              public void listen() {
                   // I will call someMethod of SomeClass:
                   SomeClass.this.someMethod();
              }
          });
     }
}

Upvotes: 3

danben
danben

Reputation: 83320

.class refers to the Class object corresponding to your instance's class. Java keeps one Class around in memory per referenced type.

Here is the Javadoc for Class: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html

The only time I have seen SomeClass.this used is when you are dealing with nested classes, and need to refer to the instance of the outer class from the inner class. See here for an example: http://juixe.com/techknow/index.php/2009/04/07/java-nested-inner-class-this/

Upvotes: 1

Dan Dyer
Dan Dyer

Reputation: 54505

The .class syntax refers to a particular instance of the Class class.

The .this syntax is usually used from within inner classes to refer to the enclosing instance of the top-level class. If you used just this from within an inner class it would refer to the instance of the inner class and not the enclosing class.

Upvotes: 1

Related Questions