代码之家  ›  专栏  ›  技术社区  ›  Addev

如何在android api<24的lambda中包装对象

  •  4
  • Addev  · 技术社区  · 8 年前

    我想迭代一个集合,覆盖每个项。

    Collection<Listener> listeners = ....
    
    interface Listener {
    
        void onEventReceived();
    
        void onShutDown();
    }
    

    代码可以是:

    void notifyShutdown() {
        for(Listener listener:listeners){
            listener.onShutDown();
        }
    }
    

    我想获取java8 lambdas,所以我声明了一个助手接口:

    interface WrapHelper<T> {
        void performAction(T item);
    }
    

    和通知方法

    public void notifyListeners(WrapHelper<Listener> listenerAction) {
        for (Listener listener : listeners) {
            listenerAction.performAction(listener);
        }
    }
    

    所以我可以声明如下方法:

    public void notifyEventReceived() {
        notifyListeners(listener -> listener.onEventReceived());
    }
    
    public void notifyShutDown() {
        notifyListeners(listener -> listener.onShutDown());
    }
    

    我的问题是:我需要声明接口吗 WrapHelper 我自己在android api<24中已经有了一个这样的类。

    谢谢

    1 回复  |  直到 7 年前
        1
  •  3
  •   maheryhaja    7 年前
    推荐文章