Do toString side effects get applied in java debugging?

喜欢而已 提交于 2019-12-11 07:35:13

问题


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.



来源:https://stackoverflow.com/questions/5494488/do-tostring-side-effects-get-applied-in-java-debugging

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