Java Generics, Create an instance of Class<T>

耗尽温柔 提交于 2020-01-03 08:56:13

问题


I am trying to write a generic method for deserializing json into my model. My problem is that I don't know how to get Class from the generic type T. My code looks something like this (and doesn't compile this way)

public class JsonHelper {

    public <T> T Deserialize(String json)
    {
        Gson gson = new Gson();

        return gson.fromJson(json, Class<T>);
    }
}

I tried something else, to get the type, but it throws an error I had the class as JsonHelper<T> and then tried this

Class<T> persistentClass = (Class<T>) ((ParameterizedType)getClass()
    .getGenericSuperclass())
    .getActualTypeArguments()[0];

The method signature looks like this

com.google.gson.Gson.fromJson(String json, Class<T> classOfT)

So, how can I translate along T so that when I call JsonHelper.Deserialize<MyObject>(json); I get an instance of the correct object?


回答1:


You need to get a Class instance from somewhere. That is, your Deserialize() method needs to take a Class<T> as a parameter, just like the underlying fromJson() method.

Your method signature should look like Gson's:

<T> T Deserialize(String json, Class<T> type) ...

Your calls will look like this:

MyObject obj = helper.Deserialize(json, MyObject.class);

By the way, the convention to start method names with a lowercase letter is well established in Java.




回答2:


Unfortunately, the way Java handles generics, you cannot get the class like you're asking. That's why Google's stuff asks specifically for the class as an argument. You'll have to modify your method signature to do the same.



来源:https://stackoverflow.com/questions/5045829/java-generics-create-an-instance-of-classt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!