It cannot work because Number
is an abstract class that doesn't provide any generic method allowing to parse a String
into the corresponding Number
implementation. You will need to provide your own method as next for example:
public class NumberParser {
public static <T extends Number> T parseNumber(String val, Class<T> type) {
if (type == Double.class) {
return (T) Double.valueOf(val);
} else if (type == Float.class) {
return (T) Float.valueOf(val);
} else if (type == Integer.class) {
return (T) Integer.valueOf(val);
} else if (type == Long.class) {
return (T) Long.valueOf(val);
}
throw new IllegalArgumentException("Unknown number type");
}
}
NB: This generic parser is not meant to be perfect, it just shows the idea.
Then your method will be:
public static <T extends Number> T[] parseString(String[] arr, Class<T> type){
return Arrays.stream(arr).map(s -> NumberParser.parseNumber(s, type))
.toArray(length -> (T[]) Array.newInstance(type, length));
}
You will then be able to parse your array of String
generically as next:
String[] values = {"1", "2", "3"};
Integer[] result = parseString(values, Integer.class);
for(Integer i : result) {
System.out.println(i);
}
Output:
1
2
3