Is there a way to disable short circuit evaluation in Java?

谁说我不能喝 提交于 2019-12-01 03:06:41

There is no compiler or JVM option for changing the semantics of boolean expression evaluation.

If you cannot modify the source, possible (albeit not guaranteed) options include:

  • Creatively recreate the conditions you seek to test via elaborate setup of preconditions.
  • Use mock objects.
  • Hack the compiler.
  • Hack the JVM.
  • Twiddle the byte code.

Sorry, those are all much more difficult than a compiler/JVM option or modifying the source. Further, the last three options (as well as the requested compiler/JVM option or modifying the source) violate proper testing protocol of not modifying what's being tested.

In order to disable short-circuit use single '&' or '|' rather than two:

boolean ret = a() & b() & c() & d() & e();

The single & advice is excellent - to explain why it works:

boolean ret = a() && b() && c() && d() && e();

This call is using Logical And on the returned values from the methods. It knows that if any of the results is false then the final result is false so it can return immediately. 'Lazy evaluation' is a standard computing optimization to avoid doing un-needed processing.

boolean ret = a() & b() & c() & d() & e();

This is replacing the logical operation with an arithmetic one - the bitwise operator. If this was working on integers then it would and all the individual bits of the integers together. In the case of a boolean though there are only true or false values but it is still evaluated as an arithmetic expression and hence all parts of the expression are evaluated.

So for boolean values & and && give the same logical result, but they are processed differently internally, which happens to give the behavior you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!