inner class non-final variable java

前端 未结 4 1537
滥情空心
滥情空心 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:06

    You can simply create an inner class instead of an anonymous one (like you are currently doing). Then you have a constructor and any other methods you want to set your members. No hackiness required (like the array of 1 case).

    I find this cleaner if the class requires any exchange of data with its outer class, but admit it is a personal preference. The array of 1 idiom will work as well and is more terse, but frankly, it just looks fugly. I typically limit anonymous inner classes to those that just perform actions without trying to update data in the outer class.

    For example:

    private MyListener listener = new MyListener();
    
    void onStart(){
      bt.setOnClickListener(listener);
    }
    
    class MyListener implements OnClickListener
    { 
        String name;
        int value;
    
        void setName(String newName)
        {
            name = newName;
        }
    
        void setValue(int newValue)
        {
            value = newValue;
        }
    
        public void onClick(View v) 
        {
            // Use the data for some unknown purpose
        }
    }
    

    If there are multiple threads involved, then appropriate synchronization will have to be used as well.

提交回复
热议问题