V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
esolve
V2EX  ›  问与答

Java8 里 接口的静态方法有啥用?

  •  
  •   esolve · 2017-06-05 19:37:43 +08:00 · 1435 次点击
    这是一个创建于 2525 天前的主题,其中的信息可能已经有所发展或是发生改变。

    实现这个接口的类或者类实例不能调用这个静态函数 那这个静态函数有啥意义?

    1 条回复    2017-06-05 20:11:52 +08:00
    ewBuyVmLZMZE
        1
    ewBuyVmLZMZE  
       2017-06-05 20:11:51 +08:00
    類似 Scala 的 Trait,第一是函數式 Lambda 基本是基於 default 實現的。第二就是類似裝飾功能,增加方法,同時不用擔心菱形繼承。

    ```java
    /**
    * A common helper interface for easy handle retrofit request
    * Inspired by scala's Trait design
    */
    public interface RetrofitCallAdaptor {

    /**
    * Helper method to generate a real rest network request, use it as you wish
    *
    * @param retrofitCall the retrofit {@link Call} interface instance
    * @param <T> the implicit type of response
    * @return the converted response if request success, otherwise the {@link RetrofitRequestFailedException} would be thrown
    */
    default <T> T execute(Call<T> retrofitCall) {
    try {
    Response<T> response = retrofitCall.execute();
    if (response.isSuccessful()) {
    return response.body();
    }
    ResponseBody errorBody = response.errorBody();
    // Null would be present only if the request is successful. Add null check only to make sonar happy
    throw new RetrofitRequestFailedException(errorBody == null ? "请求失败" : errorBody.string(), ErrorCode.NET_REQUEST_ERROR);
    } catch (IOException e) {
    throw new RetrofitRequestFailedException(e, ErrorCode.NET_REQUEST_SUSPEND);
    }
    }
    }

    ```

    比如我有一個方法,很多類都需要用,他們都有自己的特殊父類,不好擴展出一個抽象類。我又不想寫一個 Utils,那麼用接口就是最方便的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   873 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:14 · PVG 03:14 · LAX 12:14 · JFK 15:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.