简体   繁体   中英

Class type reference not pass in java generic class or method

This is the method which call the generic class method.

ServiceHandler<MyClass> serviceHandler = new ServiceHandler<MyClass>();
    List<MyClass> res = serviceHandler.genericGetAll("https://api.github.com/users/hadley/orgs", MethodTypes.GET.toString(), null);

Here is the generic class with generic method

public class ServiceHandler<T>{
 public ServiceHandler() {

    }
 public 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 List<T> createListResponseHandler(String string_response) {
        return gson.fromJson(string_response, new TypeToken<List<T>>() {
        }.getType());
    }

Now the problem is I never get the MyClass reference in T. Where I am doing wrong? . I have done lots of google but still not found the solution.

My question is how to get MyClass reference in T. Because I need to serialized the data using gson.

I have tried. But still no solution

List<MyClass> res = serviceHandler.<MyClass>genericGetAll("https://api.github.com/users/hadley/orgs", MethodTypes.GET.toString(), null);

Generic type tokens don't work.

You need to pass in the new TypeToken<List<MyClass>>() {} as a constructor parameter to ServiceHandler :

public class ServiceHandler<T> {
  private final TypeToken<List<T>> typeToken;

  public ServiceHandler(TypeToken<List<T>> typeToken) {
    this.typeToken = typeToken;
  }

  // ...

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

and instantiate using:

ServiceHandler<MyClass> serviceHandler =
    new ServiceHandler<>(new TypeToken<MyClass>() {});

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