java的接口回调

我不好说清接口回调的这些晦涩的概念。

我只知道它的使用及一些作用。

下面是一个案例。

我们首先定义一个接口

public interface CallBack {

    void call(T t);

}

写个test

@Data
public class XiaoMing {
    private String msg;

    public XiaoMing(){}
    public XiaoMing(String msg){this.msg = msg;}

    public void eat(CallBack callBack) throws Exception{
        System.out.println("小明还在吃饭");
        Thread.sleep(5000);
        callBack.call(new XiaoMing("小明吃完饭了,小明觉得饭很好吃"));
    }

    public static void main(String[] args) throws Exception{
        new XiaoMing().eat(o -> System.out.println(o.getMsg()));
    }
}

看下控制台输出

小明还在吃饭
小明吃完饭了,小明觉得饭很好吃

这就是接口的回调,在方法执行体里特定的位置进行插入,当事件执行完成到这里的时候就会触发接口的回调方法。

 

你可能感兴趣的:(java,接口,回调,java,接口)