我正在尝试从接口获取方法
我了解了getMethod()函数,并按文档所述
public Method getMethod(String name, Class<?>... parameterTypes)
是java.lang.Class.getMethod()方法的声明
我对使用简单类型(例如
)的方法没有任何疑问Call<ApiR<SelfVM>> Get(String value);
在这里传递 String.class 可以正常工作
但是当方法需要通用类时,我对此感到有点困惑,并且
在
之类的方法中,我应该传递什么而不是 parameterTypesCall<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;
}
}
这是我尝试过的……
CalculateResult函数:
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);