Java:在不改变其类型的情况下乘以泛型数 [英] Java: multiply generic Number without changing its type

查看:57
本文介绍了Java:在不改变其类型的情况下乘以泛型数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中有没有办法实现这个方法?

Is there a way in Java to implement this method?

public static <T extends Number> T doubleOf(T number){
    //I don't know...
}

谢谢

推荐答案

如其他答案所述,没有通用的解决方案.除此之外,对于某些Number 子类,您要实现的操作可能没有很好地定义.例如,AtomicInteger 的倍数是多少?它是具有相乘值的同一个实例吗?或者 AtomicInteger 的新实例?还是一个新的普通 Integer?理论上,可能存在Number的子类不允许自由创建新实例.

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.

这篇关于Java:在不改变其类型的情况下乘以泛型数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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