java - How to change my method to a generic method? -


now write common way jsonobject data key.how change generic method?now have change type every time when call method.

string a= (string) obddevicetool.getresultdata(result, "a", string.class); double b= (double) obddevicetool.getresultdata(result, "b", double.class); public static object getjsonobjectdata(jsonobject result,string key,object type){      if (result.containskey(key)) {          if(type.equals(string.class))             return  result.getstring(key);         if(type.equals(double.class))             return  result.getdouble(key);         if(type.equals(long.class))             return  result.getlong(key);         if(type.equals(integer.class))             return  result.getint(key);     }     return null; } 

private static <t> t getjsonobjectdata(jsonobject result, string key, class<t> type) {     object value = result.get(key);     return type.cast(value); } 

what must aware of:

  • a jsonexception bubble if key doesn't exist in result
  • a classcastexception bubble if type doesn't match real type of value

feel free handle these level above if necessary.


Comments