Saw this line in a class method and my first reaction was to ridicule the developer that wrote it.. But then, I figured I should make sure I was right first.
public void dataViewActivated(DataViewEvent e) {
if (this != null)
// Do some work
}
Will that line ever evaluate to false?
No. To call a method of an instance of a class, the instance has to exist. The instance is implicitly passed as a parameter to the method, referenced by
this
. Ifthis
wasnull
then there'd have been no instance to call a method of.In static class methods,
this
isn't defined sincethis
is associated with instances and not classes. I believe it would give a compiler error to attempt to usethis
keyword in static context.It's not enough that the language enforces it. The VM needs to enforce it. Unless the VM enforces it you could write a compiler that does not enforce the null check prior to calling the method written in Java. The opcodes for a instance method invocation include loading the this ref on to the stack see: http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14787. Substituting this for a null ref would indeed result in the test being false
No never, the keyword 'this' itself represents the current alive instance (object) of that class within the scope of that class, with which you can access all its fields and members (including constructors) and the visible ones of its parent class.
And, more interestingly, try setting it:
Think about it? How can it be possible, won't it be like cutting the branch you are sitting on. Since keyword 'this' is available within the scope of the class thus as soon as you say this = null; anywhere within the class then you are basically asking JVM to free the memory assigned to that object in the middle of some operation which JVM just can't allow to happen as it needs to return back safely after finishing that operation.
Moreover, attempting
this = null;
will result in compiler error. Reason is pretty simple, a keyword in Java (or any language) can never be assigned a value i.e. a keyword can never be the left value of a assignment operation.Other examples, you can't say:
No it can't. If you're using
this
, then you're in the instance sothis
isn't null.The JLS says :
If you invoked a method from an object, then the object exists or you would have a
NullPointerException
before (or it's a static method but then, you can't usethis
in it).Resources :
this
keywordWhen you invoke a method on
null
reference, theNullPointerException
will be thrown from Java VM. This is by specification so if your Java VM strictly complies to the specification,this
would never benull
.