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?
tl;dr, "this" can only be called from a non-static method and we all know that a non-static method is called from some sort of object which cannot be null.
It's like asking yourself "Am I alive?"
this
can never be nullIf you compile with
-target 1.3
or earlier, then an outerthis
may benull
. Or at least it used to...A normal
this
can never benull
in real Java code1, and your example uses a normalthis
. See other the other answers for more details.A qualified
this
should never benull
, but is possible to break this. Consider the following:When we want to create an instance of
Inner
, we need to do this:The output is:
showing that our attempt to create an
Inner
with anull
reference to itsOuter
has failed.In fact, if you stick within the "Pure Java" envelope you cannot break this.
However, each
Inner
instance has a hiddenfinal
synthetic field (called"this$0"
) that contains the reference to theOuter
. If you are really tricky, it is possible to use "non-pure" means to assignnull
to the field.Unsafe
to do it.Either way you do it, the end result is that the
Outer.this
expression will evaluate tonull
2.In short, it is possible for a qualified
this
to benull
. But it is impossible if your program follows the "Pure Java" rules.1 - I discount tricks such as "writing" the bytecodes by hand and passing them off as real Java, tweaking bytecodes using BCEL or similar, or hopping into native code and diddling with the saved registers. IMO, that is NOT Java. Hypothetically, such things might also happen as a result of a JVM bug ... but I don't recall every seeing bug reports.
2 - Actually, the JLS does not say what the behavior will be, and it could be implementation dependent ... among other things.