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

时间:2016-08-09 01:59:00

标签: 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;
}

3 个答案:

答案 0 :(得分:3)

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

您必须注意的事项:

  • 如果JSONException
  • 中不存在keyresult将会冒出来
  • 如果ClassCastExceptiontype
  • 的实际类型不匹配,value会冒出来

如有必要,请随意处理以上的

答案 1 :(得分:2)

通过@Spotted的回答,我会使用策略模式并执行以下操作:

private static final Map<Class<?>, BiFunction<JSONObject, String, Object>> converterMap =
  initializeMap();

private static Map<Class<?>, BiFunction<JSONObject, String, Object>> initializeMap() {
  Map<Class<?>, BiFunction<JSONObject,String, Object>> map = new HashMap<>();
  map.put(String.class, (jsonObject, key) -> jsonObject.getString(key));
  map.put(Integer.class, (jsonObject, key) -> jsonObject.getInt(key));
  // etc.
  return Collections.unmodifiableMap(map);
}

private static <T> Optional<T> getJSONObjectData(JSONObject json, String key, Class<T> type) {

  return
    Optional.ofNullable(converterMap.get(key))
    .map(bifi -> bifi.apply(json, key))
    .map(type::cast);
}

现在您有一个转换器映射,其中键是目标类型。如果您的类型存在转换器,则使用它,并以正确的类型返回您的对象。否则,返回Optional.empty()。

这是一个应用 Effective Java (2nd Edition)项目29:
Consider typesafe heterogeneous containers

答案 2 :(得分:1)

JSONObject有一个返回对象的方法。

Integer i = (Integer) result.get("integerKey");
String s = (String) result.get("stringKey");
Double d = (Double) result.get("doubleKey");

result是您的JSONObject对象。