Given an array of strings representing values and another string representing a primitive type, I need to parse the values strings into an array of the give primitive type, e.g. "double" and ["1", "2", "3"] would become [1.0, 2.0, 3.0].
The first solution that comes to mind would look something like this:
String format = "int16";
String[] values = {"1", "2", "3"};
switch (format)
{
case "int16":
short[] short_values = new short[values.length];
for (int i = 0; i < values.length; i++) short_values[i] = Short.parseShort(values[i]);
foo(short_values);
break;
}
While this works, I can't help but feel like there is a more elegant way of doing this. Is there some way in Java to store a reference to a static method and a reference to a primitive type so that you could so something like this:
Functor parser;
Type type;
switch (format)
{
case "int16":
parser = Short.parseShort;
type = short;
break;
}
List<type> value_list = new ArrayList<>();
for (String value : values) value_list.add(parser(value));
foo(value_list.toArray(new type[0]);
Assuming that's not possible, is there any other way that I might be able to improve upon the first solution?
Thanks