Do toString side effects get applied in java debug

2019-08-04 07:19发布

问题:

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.