Setting outer variable from anonymous inner class

后端 未结 9 861
臣服心动
臣服心动 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:52

    You need a 'container' to hold your value. You, however, do not have to create a container class. You may use classes in the java.util.concurrent.atomic package. They provide an immutable wrapper for a value along with a set and a get method. You have AtomicInteger, AtomicBoolean, AtomicReference (for your objects) e.t.c

    In the outer method:

    final AtomicLong resultHolder = new AtomicLong();
    

    In the anonymous inner class method

    long result = getMyLongValue();
    resultHolder.set(result);
    

    Later in your outer method

    return resultHolder.get();
    

    Here's an example.

    public Long getNumber() {
       final AtomicLong resultHolder = new AtomicLong();
       Session session = new Session();
       session.doWork(new Work() {
           public void execute() {
               //Inside anonymous inner class
               long result = getMyLongValue();
               resultHolder.set(result);
           }
       });
       return resultHolder.get(); //Returns the value of result
    }
    

提交回复
热议问题