Java generics and number classes
I want to create a method to compare a number, but can have an input of any subclass of a number
I see this in the following ways:
public static <T extends Number> void evaluate(T inputNumber) { if (inputNumber >= x) { ... } }
Before I can perform the comparison, I need to get the actual primative. The number class has a method to extract this for each primative, but I want a clean way to select the correct one
Is that possible?
Cheers!
Solution
Unfortunately, there is no way to get the original type from the wrapper type without resorting to the if / else block
The problem is that it is impossible to implement this method in a general way Here are some seemingly possible methods that you can expect to find in the number class:
public abstract X getPrimitiveValue();
That would be good, wouldn't it? But this is impossible No possible X may be an abstraction of int, float, double, etc
public abstract Class<?> getCorrespondingPrimitiveClass();
This will not help because there is no way to instantiate the original class
So the only thing you can do is that all types have in common is to use the longvalue () or doublevalue () method, but if you are dealing with the wrong type, you will lose information
So no: Java digital hierarchy is just not suitable for solving these problems in a general way