简体   繁体   中英

Is this in any way useful if (this != null)?

I came across some tests that included code like this:

if (this != null) {
    do something
}

Is this if clause of any use? Is there a purpose I don't get that makes this useful?

this在Java中永远不会为null ,因此这种代码永远不会有用。

In Java the this keyword can only be used in a non-static method of a class.

Thus, if you are ever running code in the method, this cannot ever be null because you are guaranteed to have an instance of that object, otherwise the method would have never been able to be called.

The programmer was looking for a fancier way to write:

if (true) {

}

You can't use "this" in a static environment that is the only place where "this" could be null.

You can call a static method or variable without an object, without an instance. "this" points to the current instance of the class. You can only use "this" if you have an object, so it will never be null.

I'm a pretty clueless programmer, so don't believe a word I say (and correct me if I'm wrong!), but it calls to mind cogito ergo sum -- I think, therefore I am. Descartes called it "the first and the most certain which presents itself to whoever conducts his thoughts in order." Similarly, that this != null seems to be (in Java, anyway, from the sound of it) among the most trivial conclusions code can reach. Neat!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM