现在我编写一种从密钥中获取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)
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)
您必须注意的是:
JSONException
则会冒泡key
result
ClassCastException
则会冒泡type
value
如有必要,请随意在更高级别上处理这些内容。
归档时间: |
|
查看次数: |
437 次 |
最近记录: |