I struggled with this for a while and have not yet found an answer. As a result, my brain got a little confused, so forgive me if I make a dumb mistake.
I am trying to implement a typed INI analyzer that will parse this file:
[section1] <int>intkey=0 <float>floatkey=0.0 <str>stringkey=test [section2] <float>x=1.0 <float>y=1.0 <float>z=0.0
In doing so, I have a central class called Config , which handles the basic read and write operations. One of the Config methods is called get(String section, String key) , which ideally should return a value corresponding to the required key pair pair, for example:
Config cfg = new Config("test.ini"); cfg.get("section2", "x"); // 1.0, not "1.0" or some Object that technically represents the float cfg.get("section1", "intkey"); // 0 cfg.get("section1", "strkey"); // "test"
I am currently using enum to handle converting String to various types using the abstract method, overridden by different types:
enum Type { INTEGER ("int") { public Object parse(String value) { try { return Integer.parseInt(value); } catch (NumberFormatException e) { return null; } } }, FLOAT ("float") { public Object parse(String value) { try { return Float.parseFloat(value); } catch (NumberFormatException e) { return null; } } }, STRING ("str") { public Object parse(String value) { return value; } }; public final String name; Type(String name) { this.name = name; } private static HashMap<String, Type> configMap = generateConfigMap(); private static HashMap<String, Type> generateConfigMap() { HashMap<String, Type> map = new HashMap<String, Type>(); for (Type type : Type.values()) map.put(type.name, type); return map; } public static Type get(String name) { return configMap.get(name); } abstract public Object parse(String value); }
Unfortunately, parse(String value) returns an object, and when transferring from Config , a listing or similar is required, and ideally it will be self-sufficient.
If I am going to do it completely wrong, and there is a more flexible or easier way to encode it, please let me know. I am open to suggestions. Although I would like to know if there is a way to do this. Maybe with generics ...?
Note. I know that I am missing imports and the like. This is not what I am posting here.