Setting outer variable from anonymous inner class

后端 未结 9 850
臣服心动
臣服心动 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 07:57

    Long is immutable. If you use a mutable class, holding a long value, you can change the value. For example:

    public class Main {
    
    public static void main( String[] args ) throws Exception {
        Main a = new Main();
        System.out.println( a.getNumber() );
    }
    
    public void doWork( Work work ) {
        work.doWork();
    }
    
    
    public Long getNumber() {
        final LongHolder result = new LongHolder();
        doWork( new Work() {
            public void doWork() {
                result.value = 1L;
            }
        } );
        return result.value;
    }
    
    private static class LongHolder { 
        public Long value; 
    }
    
    private static abstract class Work {
        public abstract void doWork();
    }
    
    }
    

提交回复
热议问题