我可能會讓某些人失明,但我仍然會開槍。通用類的類別
我知道我可以做:
Class<Response> c = Response.class;
要獲得對象的類。假設Response對象是Response<T>
我想要做類似下面的
Class<Class<User>> c = Response<User>.class;
我充滿問題:
public class RequestHelper<T> extends AsyncTask<String, Response, T> {
@Override
protected T doInBackground(String... strings) {
...
Response <T> r = objectMapper.readValue(result, Response.class);
return r .getResponse();
}
}
//and
public class Response <R> {
private R response;
public R getResponse() {
return response;
}
}
但參數在上面的分配還沒有被指定。理論上,正確的方法將需要:
public class RequestHelper<T> extends AsyncTask<String, Response, T> {
@Override
protected T doInBackground(String... strings) {
...
Response <T> r = objectMapper.readValue(result, Response <T>.class);
return r.getResponse();
}
}
但是,這會生成「無法從參數化類型中選擇」lint錯誤。
我也可以把類的構造函數:
public class RequestHelper<T> extends AsyncTask<String, Response, T> {
....
public RequestHelper(Class<Class<T>> tClass){
this.tClass = tclass;
}
@Override
protected T doInBackground(String... strings) {
...
Response <T> r = objectMapper.readValue(result, tclass);
return r.getResponse();
}
}
// where the init of the class would have been:
new RequestHelper<User>(Response<User>.class);
[Type erasure](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html) - 在運行時無法獲取有關泛型類型參數的信息,因爲它不會編譯後不存在。明確傳入一個類是一個常用的解決方法。 – khelwood 2014-09-26 19:29:20
Jackson爲此提供了類型標記。 – 2014-09-26 19:52:24
我認爲你不能在一個類中捕獲泛型參數,但是你可以在一個子類中捕獲泛型參數。我認爲這可能是@SotiriosDelimanolis所指的。 – Jason 2014-09-26 20:26:26