Implementing an interface with two abstract methods by a lambda expression

前端 未结 4 2067
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:22

    I usually create a static factory method directly in the interface:

    public inteface I1 {
        void show1();
        void show2();
    
        public static I1 of(Runnable show1, Runnable show2) {
            return new I1() {
                void show1() { show1.run(); }
                void show2() { show2.run(); }
            };
        }
    }
    

    Usage:

    I1 i1 = I1.of(() -> System.out.println("show1"), () -> System.out.println("show2"));
    

提交回复
热议问题