Setting outer variable from anonymous inner class

后端 未结 9 859
臣服心动
臣服心动 2020-11-28 07:03

Is there any way to access caller-scoped variables from an anonymous inner class in Java?

Here\'s the sample code to understand what I need:

public L         


        
9条回答
  •  日久生厌
    2020-11-28 08:07

    This situation arises a lot in Java, and the cleanest way to handle it is with a simple value container class. It's the same type thing as the array approach, but it's cleaner IMO.

    public class ValContainer {
        private T val;
    
        public ValContainer() {
        }
    
        public ValContainer(T v) {
            this.val = v;
        }
    
        public T getVal() {
            return val;
        }
    
        public void setVal(T val) {
            this.val = val;
        }
    }
    

提交回复
热议问题