Java短路评估 [英] Java short circuit evaluation

查看:191
本文介绍了Java短路评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为Java有短路评估,但这一行仍然抛出空指针异常:

I thought Java had short circuit evaluation, yet this line is still throwing a null pointer exception:

if( (perfectAgent != null) && (perfectAgent.getAddress().equals(entry.getKey())) ) {

在这种情况下, perfectAgent null ,所以我只想让整个表达式返回 false ,但我的应用程序仍在使用NullPointerException崩溃。

In this case perfectAgent is null, so I just want the whole expression to return false, but my app is still crashing on this line with a NullPointerException.

编辑,一般回复:

由于 perfectAgent null ,<$ c右边没有任何内容应该执行$ c>&& ,因为表达式不可能是真的。更重要的是,不可能执行 perfectAgent.getAddress(),因为 perfectAgent 不包含有效的引用(它是null和所有)。我正在尝试使用短路评估,而不必在单独的语句中检查null,因为这会使逻辑更加草率。

Since perfectAgent is null, nothing to the right of the && should be executed, as it is impossible for the expression to be true. More to the point, it is impossible to execute perfectAgent.getAddress() since perfectAgent does not contain a valid reference (it being null and all). I'm trying to use short circuit evaluation to not have to check for null in a seperate statement as that makes the logic more sloppy.

编辑2(或者,我'一个白痴):
是的,就像生活中的许多事情一样,在向世人宣布你是个白痴之后,你就找到了答案。在这种情况下,我在执行其他操作时关闭了Eclipse的autobuild而没有将其重新打开,因此我调试了与我的源不匹配的类文件。

EDIT 2 (or, I'm an idiot): Yeah, like many things in life you figure out the answer right after announcing to the world that you're a moron. In this case, I had turned off Eclipse's autobuild while doing something else and not turned it back on, so I was debugging class files that didn't match up with my source.

推荐答案

高级调试课#1:

如果遇到看似不可能的错误(例如一个与你有关Java的知识相矛盾的,请执行以下操作:

If you run into a seemingly impossible error (e.g. one that contradicts you knowledge about Java), do the following:


  • 查阅信誉良好的教科书(或更好的是,相关的标准)确认您的理解没有缺陷。 (在这种情况下,你的理解是正确的,任何一半体面的教科书都会在一分钟内证实这一点。)

  • Consult a reputable text book (or better still, the relevant standard) to confirm that your understanding is not flawed. (In this case your understanding was correct, and any half-decent textbook would confirm this in a minute.)

检查你能做的所有愚蠢事情这样做可能导致不可能的错误。比如没有保存文件,没有完成构建,运行应用程序的旧版/旧版本,位于错误的目录中等等。

Check all of the stupid things that you could have done that could cause the impossible error. Things like not saving a file, not doing a complete build, running an old / stale version of the application, being in the wrong directory, and so on.

总之,要学会怀疑自己多一点。

In summary, learn to doubt yourself a bit more.

这篇关于Java短路评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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