Java检查数值是否为short、long或int
是否可以检查 Java 11 中数值的原始类型?
假设我有一个方法
@Test
public void test1(){
short x = 10;
short y = 3;
var z = x * y // z is of int type
}
@Test
public void test1(){
short x = 10;
short y = 3;
var z = (short)x * y // z is of int type as variables are promoted
}
@Test
public void test3(){
short x = 10;
short y = 3;
var z = (short)x * (short)y // is z of primitive type short? Is there
// any way to check the type if it is short, long, int...
// I.e z instanceof ... or something similar specifically for
// primitive types?
}
回答
在 Java 中没有直接的方法来测试变量或原始值的类型。但是,您可以通过利用方法重载解析来间接地做到这一点。
给自己写一些像这样的重载方法:
public String typeOf(short arg) { return "short"; }
public String typeOf(int arg) { return "int"; }
public String typeOf(long arg) { return "long"; }
然后像这样使用它们:
public void test1(){
short x = 10;
short y = 3;
var z = x * y;
System.out.println(typeOf(z)); // in this case "int" will be printed.
}
等等。
然而这是不必要的。JLS指定了z每种情况下的类型。答案将int在每一种情况下。
a 的操作数*将被提升为intor long,结果将是intor long。在你的第二个和第三个例子中,演员表short没有区别1。
您将z成为的唯一方法short是在乘法之后进行转换;IE
z = (short)(x * y);
1 - 在这些情况下。如果强制转换导致重要位被截断,情况会有所不同;例如,如果x或者y是int等等。