Richard
Richard

Reputation: 6116

Java method parameter and return class object

I am trying to abstract the code in my previous post into a util class. Here's the util class method:

private static Gson gson = new GsonBuilder().create();

public static Class getResponseObject(String resourceResponse, String jsonObject, Class responseClass) {
    JSONObject jsonResponse = new JSONObject(resourceResponse);
    String jsonResponseToString = jsonResponse.getJSONObject(jsonObject).toString();
    return gson.fromJson(jsonResponseToString, responseClass.getClass());
}

And this is the call from another class:

UserIdentifier userIdentifier = ServiceClientUtil.getResponseObject(resourceResponse,
                                                                    "userIdentifier",
                                                                    UserIdentifier.class);

But I'm getting the following error:

Error:(68, 76) java: incompatible types: java.lang.Class cannot be converted to app.identity.UserIdentifier

How do I pass in a class object and return the same class object?

Upvotes: 1

Views: 3352

Answers (1)

Makoto
Makoto

Reputation: 106430

I think in this scenario you actually want to use something other than Class. Be careful though: it only makes sense to serialize key-value pairs (or an object representation of such) into a JSON value, since a raw Integer is not valid JSON.

What we can do is change the signature of your method to take in any object, and since Class can be typed, that becomes easier to do.

The signature of your method would be (untested):

public static <T> T getResponseObject(String resourceResponse,
                                      String jsonObject,
                                      Class<T> responseClass)

This way, we can ensure that the type we pass to this method is an instance of what we get. Remember: I'm not guaranteeing that this approach will work for flat values such as Integers, but it should ideally work for any other custom object that you create.

Upvotes: 4

Related Questions