我们可以知道对象引用是-通过使用instanceof运算符进行的测试。但是是否有任何运算符可以检查基本类型。例如:
byte b = 10;
现在,如果我仅考虑价值10
。我有什么办法可以发现它被声明为字节?
假设您是用局部变量来表示的,则当作为对象传递时,原语将始终按其包装器类型自动包装,在这种情况下为java.lang.Byte。使用反射引用局部变量是不可能的,因此您无法区分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());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句