Java泛型和Number类 [英] Java generics and the Number class

查看:110
本文介绍了Java泛型和Number类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个方法来比较一个数字,但可以有一个输入是Number的任何子类。



我已经看过在以下方式...

  public static< T extends Number> void input(T inputNumber){
if(inputNumber> = x){
...
}
}
pre>

在我可以执行比较之前,我需要得到实际的基本类型,Number类具有为每个基本类型检索此方法的方法,但是我想要一种干净的方式来选择正确的一个。



这是可能的吗?



干杯

解决方案

不幸的是,没有办法使用if / else块来从包装类型中获取原始类型。

问题在于它不可能以通用的方式实现这样的方法。下面是一些看起来可能的方法,可以在Number类中找到:

  public abstract X getPrimitiveValue(); 

这会很好,不是吗?但是这是不可能的。没有可能的X可能是 int float double 等。

  public abstract Class<?> getCorrespondingPrimitiveClass(); 

这也无济于事,因为没有办法实例化原始类。



所以你唯一能做的就是使用 longValue() doubleValue()方法,但是如果您处理的是错误的类型,则会丢失信息。

号码层次结构不适合以通用的方式解决这些问题。


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...

public static <T extends Number> void evaluate(T inputNumber) {
  if (inputNumber >= x) {
    ...
  }
}

I need to get the actual primative before I can perform the comparison, the Number class has methods to retrieve this for each primative but I want a clean way of selecting the correct one.

Is this possible?

Cheers

解决方案

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.

这篇关于Java泛型和Number类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆