说明
你的写作
public static void printBinary(T arg)
所以你声明T是扩展Number的东西.非常重要的是,请注意,关于T,我们不能再了解它.所以你只能安全地假设它是数字而不是更多(没有检查,例如使用instanceof).
接下来就是你写的
// requires long
print(Long.toBinaryString(arg));
// requires int
print(Integer.toBinaryString(arg));
但是这两种方法都不需要Number,它们需要long和int.看看他们的文档(Long,Integer).
即使我们考虑装箱,Java也只能将Long转换为long,将Integer转换为int(反之亦然).但不是Number to Long或Number to Integer.数字不一定是长整数或整数.例如,它也可以是Double.你不知道T是什么,你只知道它至少是数字类型.
实用方法
所以你需要做的是显式地将arg转换为long和int.因此,您可以使用Number提供的实用程序方法,即Number#longValue和Number#intValue:
print(Long.toBinaryString(arg.longValue()));
print(Integer.toBinaryString(arg.intValue()));
在instanceof后施放
另一种可能是施放它们.正如您已经使用instanceof检查过,T确实是Long或Integer类型,您可以安全地转换它:
print(Long.toBinaryString((Long) arg));
print(Integer.toBinaryString((Integer) arg));
在转换后,Java会自动将Long转换为long,将Integer转换为int,这称为取消装箱.或者为了使其更明确,请自行调用取消装箱方法:
print(Long.toBinaryString(((Long) arg).longValue()));
print(Integer.toBinaryString(((Integer) arg).intValue()));
笔记
准确地说,使用当前代码取消选中对Integer的强制转换.你还需要检查arg instanceof Integer,因此更安全:
if (arg instanceof Long) {
// Cast to Long is safe
} else if (arg instanceof Integer) {
// Cast to Integer is safe
} else {
// Neither Long nor Integer, for example Double
throw new IllegalArgumentException("Only Long and Integer supported.");
}