Do anonymous classes *always* maintain a reference to their enclosing instance?

前端 未结 3 1304
栀梦
栀梦 2020-11-27 17:14

I\'m working with some code where one object, \"foo\", is creating another object, \"bar\", and passing it a Callable. After this foo will return bar, and then

3条回答
  •  悲&欢浪女
    2020-11-27 18:15

    The static alternative (in this case) is not much larger (1 line):

    public class Outer {
      static class InnerRunnable implements Runnable {
          public void run() {
            System.out.println("hello");
          }
        }
      public Runnable getRunnable() {
        return new InnerRunnable();
      }
    }
    

    BTW: if you use a Lambda in Java8 there will be no nested class generated. However I am not sure if the CallSite objects which get passed around in that case hold an reference to the outer instance (if not needed).

提交回复
热议问题