我正在尝试从我读到的关于 getMethod() 函数的接口中获取一个方法,正如文档所说
public Method getMethod(String name, Class<?>... parameterTypes)
是 java.lang.Class.getMethod() 方法的声明
我对获得简单类型的方法没有任何问题,例如
Call<ApiR<SelfVM>> Get(String value);
这里传递String.class工作正常
但是当一个方法需要泛型类时,我对此有点困惑,
这是我的问题
我应该在方法中传递什么而不是parameterTypes
Call<ApiR<SelfVM>> Set(SendR<SelfVM> vm);
SendR和SelfVM类
public class SendR <T> {
private T value;
private String token;
public SendR(T value, String token) {
this.value = value;
this.token = token;
}
}
public class SelfVM {
private String id;
private String name;
private String lastName;
public SelfVM(String id, String name, String lastName) {
this.id = id;
this.name = name;
this.lastName = lastName;
}
}
这是我试过的
计算结果函数:
protected static void CalculateResult(final Object interfaceObject,
final String methodName,
final Class<?> viewModelClassType,
final Object viewModelObject,
final CalculateResultCallBack callBack) {
Method method;
Call<ApiR> result = null;
method = interfaceObject
.getClass()
.getMethod(methodName, viewModelClassType);
result = (Call<ApiR>) method.invoke(interfaceObject, viewModelObject);
}
这是我调用CalculateResult函数的地方
static SelfInterface apiService =
ApiSetting.getClient().create(SelfInterface.class);
public static void get(CalculateResultCallBack<SelfVM> callBack) {
CalculateResult(apiService, "Get", null,
null, callBack);
}
public static void set(SendR<SelfVM> vm, CalculateResultCallBack<SelfVM> callBack) {
CalculateResult(apiService, "Set", SendR.class, vm, callBack);
}
ApiSetting.getClient()
public class ApiSetting {
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
}
return retrofit;
}
}
获取和设置方法
@GET("json.txt")
Call<ApiR<SelfVM>> Get();
@PUT("json.txt")
Call<ApiR<SelfVM>> Set(SendR<SelfVM> vm);