java - How to make object return generic -
i looking @ following gson library provided google. in tutorial following have found following code snippet;
public class jsontojava { public static void main(string[] args) throws ioexception { try(reader reader = new inputstreamreader(jsontojava.class.getresourceasstream("/server1.json"), "utf-8")){ gson gson = new gsonbuilder().create(); person p = gson.fromjson(reader, person.class); system.out.println(p); } } } is possible make generic, example, if have following parameters
public object getobjectfromjsonstring(string jsonstring, class classtype){ then know class type, possible return object type or have have individual methods, convertjsontoclassa, convertjsontoclassb, convertjsontoclassc , on?
this returns whatever generic type parameter of classtype is. if invoke class<string>, returns string, etc...
public <t> t getobjectfromjsonstring(string jsonstring, class<t> classtype) { // code here } this implementation of gson#fromjson(string, class) does.
Comments
Post a Comment