我试图更好地理解Java Generics,所以我整理了一个小方法,它接受一个数字(一个扩展Number的Generic类型)并简单地显示它。
所以会发生的是,如果你试图传入一个布尔值,字符串或任何其他非数字'进入该方法,编译器将识别这个并给你一个编译错误。这很有效。
正如预期的那样,我注意到当我发送的数字对于某种类型来说太大(例如398457385作为int)时,编译器会抛出错误。但是,当尝试发送超出范围的字节时,它不会出现此类错误。因此,我关于检查它并在代码运行时动态抛出错误。这就是我遇到这个问题的地方。
因此,我在发送超出范围的字节时遇到了一些问题。据我所知,要将一个字节作为参数发送到方法中,你必须像以下那样强制转换它:
(byte)200
我希望能够检测到字节超出范围(小于-128或大于127)。这可以实现吗?
我的方法如下 - 请注意我删除了所有其他'类型' (例如Integer,Long,Float等......)为了这个问题的目的简化代码。
结果:
//These work fine
printNumber((Byte) 100); //Output: Byte is: 100
printNumber((Byte) 127); //Output: Byte is: 127
printNumber((Byte) -128); //Output: Byte is: -128
//With the following, I'm trying to get the method to display the 'Sorry, that byte out of
//range' message. However, sending in the following values yields these results:
printNumber((Byte) 200) //Output: Byte is: -56
printNumber((Byte) -300) //Output: Byte is: -44
以下是方法:
static<T extends Number> void printNumber(T params){
String myString = params.toString();
if(params.getClass()==Byte.class){
Byte num = Byte.valueOf(myString);
if(num>=Byte.MIN_VALUE || num<=Byte.MAX_VALUE)
System.out.println("Byte is: "+num);
else{
System.out.println("Sorry, that byte out of range");
}
}
}
答案 0 :(得分:3)
根据5.1.3 of the JLS部分,像这样的缩小演员将简单地丢弃除了8个最低有效位之外的所有部分。因此,(byte)200
强制转换将保留代表-56
的位,从而丢弃其余部分。
如果要执行此类边界检查,则需要在将其转换为byte
之前执行此操作。