gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:12:32 24 4
gpt4 key购买 nike

现在我写了一个通用的方法从一个键中获取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;
}

最佳答案

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

你必须知道的:

  • 如果 result 中不存在 key,则会出现 JSONException
  • 如果 typevalue 的实际类型不匹配,则会出现 ClassCastException

如有必要,请随意处理这些问题。

关于java - 如何将我的方法更改为通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38840914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com