When debuggind java code in eclipse, if you click on one of the variable names, that object gets printed. The object's toString() method is used to print it. If some toString method has a side effect and I click on a variable of that type, will the side effects of its toString get applied (and doubtlessly mess everything up)?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I think you answered your own question. Any time you call toString
, in debugging or otherwise, all side effects will occur. This is exactly why you should avoid side effects in toString.
回答2:
I imagine so. You can test this by writing some class's toString method so that it generates output to a file (or does something else that would be observable outside the debugger) and then letting the debugger display a variable of that type.
回答3:
A JVM can't choose to "apply" the side-effects or not. If the toString() method is used to get the string representation, it has to be executed, and there is no way to not execute the side-effects. After all, the side effects may affect how the string representation is calculated.