Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change my method to a generic method?

Tags:

java

generics

Now I write a common way to get the JSONObject data from a key.How to change it to a generic method?Now I have to change the type every time when I call the 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;
}
like image 906
flower Avatar asked Aug 09 '16 01:08

flower


1 Answers

private static <T> T getJSONObjectData(JSONObject result, String key, Class<T> type)
{
    Object value = result.get(key);
    return type.cast(value);
}

What you must be aware of:

  • A JSONException will bubble up if key doesn't exist in result
  • A ClassCastException will bubble up if type doesn't match the real type of value

Feel free to handle these a level above if necessary.

like image 147
Spotted Avatar answered Oct 28 '22 09:10

Spotted