Can “this” ever be null in Java?

2019-01-03 10:20发布

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?

标签: java this
10条回答
Explosion°爆炸
2楼-- · 2019-01-03 10:46

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.

查看更多
走好不送
3楼-- · 2019-01-03 10:47

It's like asking yourself "Am I alive?" this can never be null

查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-03 10:50

If you compile with -target 1.3 or earlier, then an outer this may be null. Or at least it used to...

查看更多
够拽才男人
5楼-- · 2019-01-03 10:50

A normal this can never be null in real Java code1, and your example uses a normal this. See other the other answers for more details.

A qualified this should never be null, but is possible to break this. Consider the following:

public class Outer {
   public Outer() {}

   public class Inner {
       public Inner() {}

       public String toString() {
           return "outer is " + Outer.this;  // Qualified this!!
       }
   }
}

When we want to create an instance of Inner, we need to do this:

public static void main(String[] args) {
    Outer outer = new Outer();
    Inner inner = outer.new Inner();
    System.out.println(inner);

    outer = null;
    inner = outer.new Inner();  // FAIL ... throws an NPE
}

The output is:

outer is Outer@2a139a55
Exception in thread "main" java.lang.NullPointerException
        at Outer.main(Outer.java:19)

showing that our attempt to create an Inner with a null reference to its Outer has failed.

In fact, if you stick within the "Pure Java" envelope you cannot break this.

However, each Inner instance has a hidden final synthetic field (called "this$0") that contains the reference to the Outer. If you are really tricky, it is possible to use "non-pure" means to assign null to the field.

  • You could use Unsafe to do it.
  • You could use native code (e.g. JNI) to do it.
  • You could do it by using reflection.

Either way you do it, the end result is that the Outer.this expression will evaluate to null2.

In short, it is possible for a qualified this to be null. 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.

查看更多
登录 后发表回答