Do toString side effects get applied in java debug

2019-08-04 07:26发布

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)?

3条回答
贼婆χ
2楼-- · 2019-08-04 07:37

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.

查看更多
The star\"
3楼-- · 2019-08-04 07:40

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.

查看更多
成全新的幸福
4楼-- · 2019-08-04 07:46

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.

查看更多
登录 后发表回答