简体   繁体   中英

Pass the class type in generic method java

An Interface class with the definition of TestJsonData.

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

Implementation method of interface class

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);
    }

}

Again an interface class with definition method as genericGetAll

public interface IServiceHandler
{

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

Implementation method of interface class

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

    }

The generic response is not of type class MyClass . Still not able refer to class type . The T type is still not referring as Myclass type

 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());
    }
  }

If I hard code the MyClass in gson.fromJson(string_response, new TypeToken<List<MyClass>>() . I am able to get the class type without hard code the response is like as you can see in the image.

The below code is calling the method TestJsonData().I have added the implicitly type but still not able to find the solution

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

The below image shows the response value without hard code Myclass.

没有硬编码

The below image shows the response value with hard code Myclass.

具有硬编码值

If you omit explicitly setting the type-parameter and if it could not be inferred by the compiler, then it would default to Object .

In order to explicitly set it, you should do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM