【问题标题】:Why does Retrofit use Interface instead of a normal java class?为什么 Retrofit 使用 Interface 而不是普通的 java 类?
【发布时间】:2020-01-15 11:14:46
【问题描述】:

在我的 Android 中,我使用 Retrofit 来实现一个 http 客户端。
Retrofit 使用接口来定义可能的 http 操作。

userInterface.java

UserInterface.java
public interface UserInterface {
   // Retrofit callback
   @POST("login")
   Call<Integer> signin(@Body LoginActivity.UserInfo userInfo);
}

这个 UserInterface 然后被 loginActivity.java 中的改造使用:

loginActivity.java

// It makes sense. Retrofit will use the interface as a configuration file
UserInterface userInterface = ApiClient.getApiClient().create(UserInterface.class);

ApiClient.java

public static Retrofit getApiClient(){
   if (retrofit==null){
       retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();
   }
   return retrofit;
};

我完全了解 Retrofit Client 的配置方式及其工作原理。但是,我不明白为什么 userInterface 是一个 java 接口而不是一个普通的 java 类?
我知道简而言之,这就是接口:

接口是 Java 中的引用类型。它类似于类。它是抽象方法的集合。一个类实现一个接口, 从而继承接口的抽象方法。沿着 对于抽象方法,接口也可以包含常量, 默认方法、静态方法和嵌套类型。方法体存在 仅适用于默认方法和静态方法。

编写接口类似于编写类。但是一堂课 描述对象的属性和行为。还有一个界面 包含类实现的行为。

除非实现接口的类是抽象的,否则所有的 接口的方法需要在类中定义。

我也理解了Retrofit接口的特殊作用:

您可以将接口视为配置文件,它包含信息 (方法声明,返回类型和参数,注释)关于每个 端点(将方法名称链接到 url、GET 或 POST、参数和 参数类型,返回值类型,...等等)。发动机使用 那些用于序列化参数的信息(如果需要),执行请求 并反序列化响应(如果需要)。

但是,我仍然无法向自己解释使用接口而不是普通的 java 类

【问题讨论】:

    标签: java android-studio interface retrofit retrofit2


    【解决方案1】:

    如果您查看Retrofit library 的源代码,尤其是Retrofit.java 类的create() 方法,您可以看到它们使用Java's Dynamic Proxy 方法在运行时创建类。

    这种机制需要一个接口(或接口列表)来创建具有特定行为的代理类。这就解释了为什么使用接口而不是普通的java类。

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 2023-02-09
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 2020-08-29
      • 1970-01-01
      • 2014-07-18
      • 2012-09-13
      相关资源
      最近更新 更多