Java generics and numeric types
generics, java
Solution
I agree 100% with TofuBeer. But in case you wish to avoid verbosity for time sake, this should also do:
static <T extends Number> T sloppyParseNumber(String str,Class<T> clas) {
if (clas == null) throw new NullPointerException("clas is null");
try {
if(clas.equals(Integer.class)) {
return (T) Integer.valueOf(str);
}
else if(clas.equals(Double.class)) {
return (T) Double.valueOf(str);
}
//so on
catch(NumberFormatException|NullPointerException ex) {
// force call with valid arguments
return sloppyParseNumber("0", clas);
}
throw new IllegalArgumentException("Invalid clas " + clas);
}
But purely from `T`, you cannot get the type at runtime.
Problem
I'd like to create a generic method which does effectively this: ``` class MyClass { static <T extends Number> T sloppyParseNumber(String str) { try { return T.valueOf(str); } catch (Exception e) { return (T)0; } } } ``` Now above does not compile for two reasons: there's no `Number.valueOf()` method and 0 can't be cast to `T`. Example usage: ``` String value = "0.00000001"; System.out.println("Double: " + MyClass.<Double>sloppyParseNumber(value)); System.out.println("Float: " + MyClass.<Float>sloppyParseNumber(value)); double d = MyClass.sloppyParseNumber(value); float f = MyClass.sloppyParseNumber(value); ``` Is implementing above generic method possible with Java? If yes, how? If no, what's a good alternative approach? Edit: there seems to be a few possible duplicates, but I did not find one, which covers exactly this. I'm hoping there's some trick to pull, which would allow these two operations: parse string to a `Number` subclass, and return 0 value for a `Number` subclass.