Behavior of Functional Interface and Method Reference

前端 未结 2 1663
醉酒成梦
醉酒成梦 2021-01-13 14:10

What happens when the reference of a method which belongs to a variable is destroyed?

public class Hey{
    public double bar;

    public Hey(){
        bar         


        
2条回答
  •  没有蜡笔的小新
    2021-01-13 14:26

    Your method reference is essentially equivalent to doing this:

    Hey hey = new Hey();
    Function square = new DoubleDoubleFunction(hey);
    

    where the class DoubleDoubleFunction is defined like this

    class DoubleDoubleFunction implements Function {
        private final Hey hey;
    
        public DoubleDoubleFunction(Hey hey) {
            this.hey = hey;
        }
    
        @Override
        public Double apply(Double num) {
            return hey.square(num);
        }
    }
    

    In other words, square holds a reference to the Hey.

    I don't know about eclipse, but with IntelliJ you can easily translate method references and lambdas into anonymous / static nested / inner classes to see what's going on. I find this a very instructive thing to do.

提交回复
热议问题