How to change a method to a general method?

Now I am writing a general way to get JSONObject data from a key. How to change it to a general method? Now I have to change the type every time 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; } 
+6
source share
3 answers
 private static <T> T getJSONObjectData(JSONObject result, String key, Class<T> type) { Object value = result.get(key); return type.cast(value); } 

What you should know about:

  • A JSONException will bubble if key does not exist in result
  • A ClassCastException will bubble if type does not match the actual type of value

Feel free to handle these levels above if necessary.

+3
source

Taking the answer by @Spotted a little further, I would use a strategy template and do something like this:

 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); } 

Now you have a map of converters, where the key is the target type. If a converter exists for your type, it is used, and your object is returned in the correct type. Otherwise, the Optional.empty () option is returned.

This is Effective Java Application (2nd Edition) Paragraph 29:
Consider the types of heterogeneous containers .

+2
source

JSONObject has a method that returns an object.

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

result is your JSONObject.

+1
source

All Articles