Java Generics, Create an instance of Class<T> -
i trying write generic method deserializing json model. problem don't know how class generic type t. code looks (and doesn't compile way)
public class jsonhelper { public <t> t deserialize(string json) { gson gson = new gson(); return gson.fromjson(json, class<t>); } }
i tried else, type, throws error had class jsonhelper<t>
, tried this
class<t> persistentclass = (class<t>) ((parameterizedtype)getclass() .getgenericsuperclass()) .getactualtypearguments()[0];
the method signature looks this
com.google.gson.gson.fromjson(string json, class<t> classoft)
so, how can translate along t when call jsonhelper.deserialize<myobject>(json);
instance of correct object?
you need class
instance somewhere. is, deserialize()
method needs take class<t>
parameter, underlying fromjson()
method.
your method signature should gson's:
<t> t deserialize(string json, class<t> type) ...
your calls this:
myobject obj = helper.deserialize(json, myobject.class);
by way, convention start method names lowercase letter established in java.
Comments
Post a Comment