Can I access new methods in anonymous inner class with some syntax?

前端 未结 7 2236
深忆病人
深忆病人 2020-12-01 14:48

Is there any Java syntax to access new methods defined within anonymous inner classes from outer class? I know there can be various workarounds, but I wonder if a special sy

7条回答
  •  忘掉有多难
    2020-12-01 14:59

    Funny enough, this is now allowed with var construct (Java 10 or newer). Example:

    var calculator = new Object() {
      BigDecimal intermediateSum = BigDecimal.ZERO;
      void calculate(Item item) {
        intermediateSum = Numbers.add(intermediateSum, item.value);
        item.sum= intermediateSum;
      }
    };
    items.forEach(calculator::calculate);
    

    Here with method reference, but works with dot method call as well, of course. It works with fields as well. Enjoy new Java. :-)

    I found more tricks with var and anonymous classes here: https://blog.codefx.org/java/tricks-var-anonymous-classes/

提交回复
热议问题