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));
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 .
source share