如何将我的方法更改为通用方法?

flo*_*wer 6 java generics

现在我编写一种从密钥中获取JSONObject数据的常用方法.如何将其更改为泛型方法?现在每次调用方法时都必须更改类型.

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;
}
Run Code Online (Sandbox Code Playgroud)

Spo*_*ted 3

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

您必须注意的是:

  • 如果A不存在,JSONException则会冒泡keyresult
  • 如果A与实际类型不匹配,ClassCastException则会冒泡typevalue

如有必要,请随意在更高级别上处理这些内容。