Implementing an interface with two abstract methods by a lambda expression

前端 未结 4 2029
Happy的楠姐
Happy的楠姐 2020-12-28 13:39

In Java 8 the lambda expression is introduced to help with the reduction of boilerplate code. If the interface has only one method it works fine. I

4条回答
  •  情话喂你
    2020-12-28 14:35

    You can always use composition:

    public inteface I1 {
        void show1();
        void show2();
    }
    
    public class I1Adapter {
        private final Runnable r1,r2;
        public I1Adapter(Runnable r1, Runnable r2) {this.r1=r1; this.r2=r2;}
        public void show1() {r1.run();}
        public void show2() {r2.run();}
        public static I1Adapter compose(Runnable r1, Runnable r2) {
            return new I1Adapter(r1,r2);
        }
    }
    

    No you can do (with a static import):

    I1 i1 = compose(()->foo(), ()->bar());
    

提交回复
热议问题