Java方法参数和返回类对象

Java方法参数和返回类对象,java,Java,我正试图将我的数据库中的代码抽象为一个util类。下面是util类方法: private static Gson gson = new GsonBuilder().create(); public static Class getResponseObject(String resourceResponse, String jsonObject, Class responseClass) { JSONObject jsonResponse = new JSONObject(resourc

我正试图将我的数据库中的代码抽象为一个util类。下面是util类方法:

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());
}
这是另一个类的调用:

UserIdentifier userIdentifier = ServiceClientUtil.getResponseObject(resourceResponse,
                                                                    "userIdentifier",
                                                                    UserIdentifier.class);
但我得到了以下错误:

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

如何传入一个类对象并返回同一个类对象?

我认为在这种情况下,您实际上希望使用的不是
。但是要小心:只有将键值对(或类似的对象表示)序列化为JSON值才有意义,因为原始的
整数
不是有效的JSON

我们可以做的是将方法的签名更改为接受任何对象,并且由于可以键入
Class
,因此这变得更容易

您的方法的签名将是(未经测试):

公共静态T getResponseObject(字符串resourceResponse, 字符串jsonObject, 类响应(类)
通过这种方式,我们可以确保传递给这个方法的类型是我们得到的实例。请记住:我不能保证这种方法适用于平面值,例如
Integer
s,但理想情况下,它应该适用于您创建的任何其他自定义对象。

不,这不是我想要的,因为我试图使其成为一种可重用的方法。因此,我希望能够为
responseClass
传入任何类型的类,并返回该类。例如,我应该能够传入
Integer.class
,并得到返回的值。我只是把
UserIdentifier
用作example@Richard:我不认为
Integer
会按照您希望的方式工作,但我已经修改了我的答案。太好了,这完全符合我的要求。谢谢,错误信息已经足够清楚了。你有什么不明白的?
public static <T> T getResponseObject(String resourceResponse,
                                      String jsonObject,
                                      Class<T> responseClass)