简体   繁体   English

如何创建实现通用接口的全局通用类?

[英]How to create a global generic class which implements a generic interface?

To be very honest I need to use Retofit Callback for multiple classes. 老实说,我需要对多个类使用Retofit回调。 I dont want to write the callback interface with onResponse and onFailour method in each UI page. 我不想在每个UI页面中使用onResponse和onFailour方法编写回调接口。

So I decided to write a global class which will implements the Retrofit Callback interface. 因此,我决定编写一个全局类,该类将实现Retrofit Callback接口。

But my problem is, I want to make it Generic, because there are many different ResponseParser classes which are going to use this global class. 但是我的问题是,我想使其成为通用类,因为有许多不同的ResponseParser类将使用此全局类。

I tried like below, but facing a little problem in it. 我尝试如下所示,但面临一些小问题。

public class WebAPIControler implements Callback<TResponse>{

@Override
public void onResponse(Call<TResponse> call, Response<TResponse> response) {

}

@Override
public void onFailure(Call<TResponse> call, Throwable t) {

}
}

Here compiler not able to found TResponse class. 在这里,编译器无法找到TResponse类。 here TResponse is a generic class where I want to handle all king of ResponseParser classes. 在这里TResponse是一个泛型类,我想在其中处理所有ResponseParser类之王。 So I give a name it as T or TResponse. 因此,我将其命名为T或TResponse。 Please help me how to handle this. 请帮助我如何处理。

You have to make your class as generic class first then implement generic interface. 您必须先将您的类设为通用类,然后再实现通用接口。

public class WebAPIControler implements Callback<T>{

@Override
public void onResponse(Call<T> call, Response<T> response) {

}

@Override
public void onFailure(Call<T> call, Throwable t) {

}
}

What is T? 什么是T?

E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

Source 资源

I suggest you just implement generic interface, your class is not required to be generic. 我建议您仅实现通用接口,而不必要求您的类是通用的。

UPDATE 更新

a.create Interface 创建接口

interface CustomSubscriber<T>  {
void test(T object);
}

b.Implement your interface with any object b。用任何对象实现您的界面

public class WebAPIControler implements CustomSubscriber<JsonObject>{

@Override
public void test(JsonObject object) {

}
}

As others have commented, what you're missing is the generic type declaration in public class WebAPIControler<T> . 正如其他人所评论的那样,您缺少的是public class WebAPIControler<T>的泛型类型声明。 That's why the compiler is complaining T doesn't exist. 这就是为什么编译器抱怨T不存在的原因。

public class WebAPIControler<T> implements Callback<T> {
    @Override
    public void onResponse(Call<T> call, Response<T> response) {

    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM