Java generics and the Number class

后端 未结 5 1576
一个人的身影
一个人的身影 2021-01-11 16:16

I want to create a method that compares a number but can have an input that is any of the subclasses of Number.

I have looked at doing this in the following manner..

5条回答
  •  情深已故
    2021-01-11 16:57

    Unfortunately there is no way to get the primitive type from the wrapper type without resorting to if/else blocks.

    The problem is that it just wouldn't be possible to implement such a method in a generic way. Here are some seemingly possible approaches which one could expect to find in the Number class:

    public abstract X getPrimitiveValue();
    

    This would be nice, wouldn't it? But it's impossible. There is no possible X that could be an abstraction over int, float, double etc.

    public abstract Class getCorrespondingPrimitiveClass();
    

    This won't help either, because there is no way to instantiate primitive classes.

    So the only thing you can do that is common to all types is to use the longValue() or doubleValue() methods, but either way you are losing information if you're dealing with the wrong type.

    So no: the java number hierarchy is just not suited to solve such problems in a generic way.

提交回复
热议问题