[英]Create Parameterized Type of another class from existing ParameterizedType
[英]Create parameterized type of type “Class”
我已經發現我的GSON問題全都在於以下事實:盡管我的返回類型不是參數化對象,但應該如此。 現在,我需要使用帶有參數類型的Gson.fromJson方法來指定返回類型,以便GSON可以幫我解決這個問題。
我創建了一個名為RestResponse的通用類,例如:
public class RestResponse<T> {
private String errorMessage;
private int errorReason;
private T result;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "RestResponse [errorMessage=" + errorMessage + ", result=" + result + "]";
}
/**
* Does this response contain an error?
* @return true if in error
*/
public boolean isInError(){
return getErrorMessage()!=null;
}
/**
* @return the errorMessage
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* @param errorMessage the errorMessage to set
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
/**
* The error reason code
* @return the errorReason
*/
public int getErrorReason() {
return errorReason;
}
/**
* The error reason code
* @param errorReason the errorReason to set
*/
public void setErrorReason(int errorReason) {
this.errorReason = errorReason;
}
/**
* The result of the method call
* @return the result or null if nothing was returned
*/
public final T getResult() {
return result;
}
/**
* The result of the method call
* @param result the result to set or null if nothing was returned
*/
public final void setResult(T result) {
this.result = result;
}
}
現在,我要在另一側創建結果類型。 我有一個通用方法,可用來解碼這些東西並拋出異常或返回結果。
所以我的方法是這樣的:
public Object submitUrl(String url, Class<?> clazz) throws AjApiException {
其中clazz是將在RestResponse上指定的類型。
然后,在傳遞給GSON之前,我先創建RestResponse:
Type typeOfT = new TypeToken<RestResponse<clazz>>(){}.getType(); //1-->What goes here?
RestResponse<clazz> restResponse; //2-->and here?
而且它出錯。 有人可以告訴我這些取代了爵士樂的地方嗎?
無需傳遞要包裝響應的類,而是將其指定為方法級別的通用參數。
public <T> T submitUrl(String url) throws AjApiException {
Type typeOfT = new TypeToken<RestResponse<T>>(){}.getType();
}
我最終傳入了類型而不是類。 這樣就解決了問題。
我相信您可以通過執行以下操作來創建類型:
Type typeOfT = new TypeToken<RestResponse<T>>(){}.getType();
最簡單的方法是讓方法的調用者傳遞與RestResponse<Whatever>
相對應的Type
而不是傳遞Class
對象。 他們可能會使用TypeToken
做到這一點。
否則,您可以自己構造Type
(特別是ParameterizedType
)。 您可能需要制作自己的實現ParameterizedType
的類,或者復制某些項目中使用的ParameterizedTypeImpl
私有類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.