2016-02-24 29 views
0

具有TestJsonData定義的接口類。接口類以通用方法java類傳遞類類型

public class CasAuthentication implements ICasAuthentication { 
    private IServiceHandler _iServiceHandler = null; 
    public CasAuthentication(ServiceHandler ServiceHandler) { 
     this._iServiceHandler = ServiceHandler; 
    } 

    public <T>List<T> TestJsonData() { 
     List<T> response = null; 
     return response = _iServiceHandler.<T>genericGetAll("https://api.github.com/users/hadley/orgs", MethodTypes.GET.toString(), null); 
    } 

} 

再次定義方法的接口類的

public interface ICasAuthentication { 
     <T> List<T> TestJsonData(); 
    } 

實現方法如genericGetAll

public interface IServiceHandler 
{ 

    <T>List<T> genericGetAll(String destinationUrl, String method, HashMap<String, String> params); 
} 

接口類的實現方法

public class ServiceHandler implements IServiceHandler { 
    public String response = null; 
    private static Gson gson = new Gson(); 
    public ServiceHandler() { 

    } 

通用響應不是類型MyClass。仍然無法引用類的類型。該牛逼類型仍然不是指作爲MYCLASS型

public <T> List<T> genericGetAll(String destinationUrl, String method, HashMap<String, String> params) { 
     List<T> genericResponse = null; 
     String httpResponse = httpClient(destinationUrl, method, params); 
     genericResponse = createListResponseHandler(httpResponse); 
     return genericResponse; 

    } 
private <T> List<T> createListResponseHandler(String string_response) { 
     return gson.fromJson(string_response, new TypeToken<List<T>>() { 
     }.getType()); 
    } 
    } 

如果我硬編碼在MyClass的gson.fromJson(string_response, new TypeToken<List<MyClass>>()。我能夠在沒有硬代碼的情況下獲得類的類型,就像您在圖像中看到的一樣。

在下面的代碼被調用方法TestJsonData()。我已經添加了隱式類型,但依然沒能找到解決

List<MyClass> res = _iCasAuthentication.<MyClass>TestJsonData(); 

的下面圖像示出了沒有硬代碼MYCLASS響應值。

without hard code

的下面圖像示出了具有硬編碼MYCLASS響應值。

with hardcode value

回答

1

如果省略明確設置類型參數,如果它不能由編譯器來推斷,那麼它會默認爲Object

爲了明確設置它,你應該做的:

List<MyClass> res = callingMethod.<MyClass>createListResponseHandler(""); 
+0

我已經更新了問題,你可以檢查??? –