Is there a way in Java to implement this method?
public static <T extends Number> T doubleOf(T number){
//I don't know...
}
Thanks
As mentioned in other answers, there is no general solution.
Beside others, the operation you want to implement may not be well defined for some Number subclasses. For instance, what is the multiple of AtomicInteger? Is it the same instance with a multiplied value? Or a new instance of AtomicInteger? Or a new plain Integer? Theoretically, there might be a subclass of Number that does not allow to create new instances freely.
You may test the input for some known subclasses and implement the operation for those. Something like this:
@SuppressWarnings("unchecked")
public static <N extends Number> N multiply(N number, int multiplier) {
Class<? extends Number> cls = number.getClass();
if (cls == Integer.class) {
return (N) Integer.valueOf(number.intValue() * multiplier);
}
if (cls == Long.class) {
return (N) Long.valueOf(number.longValue() * multiplier);
}
throw new UnsupportedOperationException("unknown class: " + cls);
}
I am afraid the suppression of warnings will be necessary, in some form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With