inner class non-final variable java

前端 未结 4 1547
滥情空心
滥情空心 2021-02-15 14:59

I needed to change variables inside an inner class and I got the infamous \"Cannot refer to a non-final variable inside an inner class defined in a different method\" error.

4条回答
  •  無奈伤痛
    2021-02-15 15:05

    I posted a similar answer in my other thread here. Basically the idea is to create a "wrapper" which wraps over pretty much any Object type. Since final in Java stands for "no reassignment" and not "constant", this trick pretty much works out fine. But as mentioned in the original post, make sure you tread with caution when using it in a multi-threaded environment.

提交回复
热议问题