Java泛型,创建类< T>的实例 [英] Java Generics, Create an instance of Class<T>
问题描述
我想写一个通用的方法来反序列化json到我的模型。我的问题是,我不知道如何从泛型类型T获取类。我的代码看起来像这样(不编译这种方式)
public class JsonHelper {
public< T> T Deserialize(String json)
{
Gson gson = new Gson();
return gson.fromJson(json,Class< T>);
}
}
我尝试了其他方法,它抛出一个错误,我有类作为 JsonHelper< T>
然后尝试这个
Class< T> persistClass =(Class< T>)((ParameterizedType)getClass()
.getGenericSuperclass())
.getActualTypeArguments()[0];
方法签名如下所示:
com.google.gson.Gson.fromJson(String json,Class< T> classOfT)
所以,我怎么翻译T,所以当我调用 JsonHelper.Deserialize< MyObject>(json);
我得到一个正确的实例对象?
您需要从某处获取 Class
实例。也就是说, Deserialize()
方法需要一个类< T>
作为参数, fromJson()
方法。
您的方法签名应类似于Gson的:
< T> T Deserialize(String json,Class< T> type)...
:
MyObject obj = helper.Deserialize(json,MyObject.class);
顺便提一下,用小写字母启动方法名的约定在Java中是非常成熟的。 / p>
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?
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.
这篇关于Java泛型,创建类< T>的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!