Is there a way to assign a default value to a derived class of Number, that can be passed through an int?
I am looking for an implementation for:
public <N extends Number> N getNumberWithDefault( N number, int defaultNumber );
I know it would be easy with:
public <N extends Number> N getNumberWithDefault(N number, Class<N> clazz, String defaultNumber) {
N result = number;
if (result == null) {
try {
result = clazz.cast(clazz.getDeclaredMethod("valueOf", String.class).invoke(null, defaultNumber));
} catch (Exception ex) {
LOGGER.error("Error assigning default", ex);
}
}
return result;
}
But it does not seem elegant at all. Is there any way to improve it?
UPDATE
What I wanted to know is if something like this can be done:
public <N extends Number> N getNumberWithDefault( N number ) {
return getNumberWithDefault( number, 1 );
}
Then, the same function (getNumberWithDefault(number)), could be used for all classes.
Although I think that may be possible that that way to proceed is not possible in Java