if 子句中包含多个 return 语句的函数未按预期运行?
我对 Java 编程无论如何都不陌生,但这个问题对我来说是闻所未闻的。 我有这样的代码:
private static boolean isEarlierThanAndNotReminded(Callback left, Callback right) {
if(right == null) {
return !left.isReminded();
}
else {
return !left.isReminded() && (left.getAlertStart().before(right.getAlertStart()));
}
}
好吧,问题是我在“else”子句中的行上得到了一个空指针的报告。 当我调试时,我可以看到 right
实际上是 null,但执行仍然首先落在 if 子句中,然后控制继续进入“else”子句,在那里它获得一个空指针。 我不知道我在这里缺少什么,有什么建议吗?
I'm not new to Java programming in any way, but this problem is unheard of to me.
I have this code:
private static boolean isEarlierThanAndNotReminded(Callback left, Callback right) {
if(right == null) {
return !left.isReminded();
}
else {
return !left.isReminded() && (left.getAlertStart().before(right.getAlertStart()));
}
}
Ok so the problem is that I get a report of a null pointer on the line in the "else" clause.
When I debug, I can see that right
is actually null, but still the execution land first in the if-clause and then control continues into the "else"-clause where it gets a null pointer.
I am clueless to what I am missing here, any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它可能只是编译器优化和调试器处理它的方式的函数。
它会执行第一个条件“if”,但不会实际执行返回。如果你想一想,无论怎样
'right' 的值是代码需要知道 ' !left.isRe Mind()' 的值,因此必须执行该语句。我敢打赌,如果您在 if 语句之前启动函数
,然后将新的布尔值放入 return 语句中,您会在调试器中看到不同的执行路径。
It's probably just a function of the optimisation of the compiler and the way the debugger handles it.
It's going to the 'if' first condition but not actually executing the return. If you think about it, whatever
the value of 'right' is the code needs to know the value of ' !left.isReminded()', so that statement has to be executed. I bet that if you started your function with
before the if statement and then did put that new boolean into your return statements, you would see a different execution path in the debugger.
这是一个有点混乱的 If 语句,我可能没有正确的逻辑,但这对你来说应该更有意义:
}
你想检查 right 是否不为空,如果不是,则意味着你有一个 'right ' 回调,所以使用正确的对象,否则你假设你有一个左回调并使用它。
这段代码:
需要您检查左右空检查:
所以如果我有这个权利,您最终会得到:
Thats a bit of a mixed up If statement, I may not have your logic right but this should make more sense to you:
}
You want to check that right isn't null, if it isn't it means you have a 'right' callback so use the right object , else you assume you have a left callback and use this.
This bit of code:
needs you to check for both left and right null checks:
So if I have this right you would end up with:
right
并不是else
子句中唯一可以为null
的引用。left.getAlertStart()
也可能为null
—— 这很可能是导致异常的原因。The
right
is not the only reference which can benull
in theelse
clause. Theleft.getAlertStart()
might benull
as well -- that's likely what causes the exception.