可以“这个”在Java中永远是空的? [英] Can "this" ever be null in Java?

查看:156
本文介绍了可以“这个”在Java中永远是空的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类方法中看到这一行,我的第一反应是嘲笑编写它的开发人员..但是,我想我应该确保我是第一个。

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 it can't. If you're using this, then you're in the instance so this isn't null.

JLS说:


当用作主表达式时,关键字this表示a value是对调用实例方法的对象(第15.12节)或对正在构造的对象的引用。

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.

如果你从一个对象调用一个方法,那么该对象就存在了,或者你之前会有一个 NullPointerException (或者它是一个静态方法但是你不能使用 in。)

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 use this in it).

资源:

  • JLS - this keyword

这篇关于可以“这个”在Java中永远是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆