gpt4 book ai didi

java - 为什么Retrofit使用Interface而不是普通的java类?

转载 作者:行者123 更新时间:2023-11-30 05:19:49 24 4
gpt4 key购买 nike

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

userInterface.java

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

然后在loginActivity.java中通过retrofit使用这个UserInterface:

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 接口(interface)而不是普通的 java 类?
我知道,简而言之,这就是界面:

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

我也了解了Retrofit界面的特殊作用:

You can see the interface as a configuration file, it holds info (method declaration , return type and params, annotations) about each endpoint (link a method name to url, GET or POST, parameters and parameter types, return value type , ... and more). the engine uses those info to serialize parameters (if needed), execute the request and deserialize the response (if needed).

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

最佳答案

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

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

关于java - 为什么Retrofit使用Interface而不是普通的java类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59750268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com