有没有办法检查instanceof基元变量java

我们可以通过使用instanceof运算符知道对象引用是一个测试。 但是有没有运算符来检查原始类型。 例如:

byte b = 10; 

现在,如果我只考虑值10 。 有什么方法可以发现它被声明为一个字节?

局部变量

假设你的意思是局部变量,只要在这种情况下作为对象java.lang.Byte传递,原语将始终由其包装类型自动包装。 使用reflection引用局部变量是不可能的,因此您无法区分Byte和byte或Integer和int等。

 Object bytePrimitive = (byte) 10; System.out.println("is a Byte ? " + (bytePrimitive instanceof Byte)); System.out.println("Check class = " + (bytePrimitive.getClass())); // false because class in this case becomes Byte, not byte. System.out.println("Primitive = " + (bytePrimitive .getClass().isPrimitive())); 

字段

但是,如果您正在讨论类中的字段,那么事情会有所不同,因为您可以获得实际声明类型的句柄。 然后,您可以按预期使用java.lang.Class.isPrimitive(),类型将为byte.class。

 public class PrimitiveMadness { static byte bytePrimitiveField; static Byte byteWrapperField; public static void main(String[] args) throws Exception { System.out.println("Field type = " + PrimitiveMadness.class.getDeclaredField("bytePrimitiveField").getType()); System.out.println("Is a byte = " + (PrimitiveMadness.class.getDeclaredField("bytePrimitiveField").getType() == byte.class)); System.out.println("Is a primitive? = " + PrimitiveMadness.class.getDeclaredField("bytePrimitiveField").getType().isPrimitive()); System.out.println("Wrapper field = " + PrimitiveMadness.class.getDeclaredField("byteWrapperField").getType()); } } 

如果你真的想玩文字……

  if(Byte.class.isInstance(10)) { System.out.println("I am an instance of Byte"); } if(Integer.class.isInstance(10)) { System.out.println("Ups, I can also act as an instance of Integer"); } if(false == Float.class.isInstance(10)) { System.out.println("At least I am not a float or double!"); } if(false == Byte.class.isInstance(1000)) { System.out.println("I am too big to be a byte"); } 
 byte b = 10; Object B= b; if (B.getClass() == Byte.class) { System.out.println("Its a Byte"); } 

注意:字节是最终的,因此instanceof等同于类的相等性。

现在,如果你尝试:

 Object ref = 10; System.out.println(ref.getClass()); //class java.lang.Integer Object ref = 10.0; System.out.println(ref.getClass()); //class java.lang.Double Object ref = 10L; System.out.println(ref.getClass()); //class java.lang.Long 

等等…