通过使用instanceof操作符,我们可以知道对象引用是一个测试。但是,是否有任何操作符来检查基元类型。例如:
byte b = 10;现在,如果我只考虑值10。有没有办法让我知道它是被声明为字节的?
发布于 2014-12-10 20:25:37
局部变量
假设您所说的局部变量,无论何时作为对象传递时,原语都将自动由其包装器类型包装,在本例中为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());
}
}发布于 2014-12-10 21:56:13
如果你真的想玩文字游戏...
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");
}发布于 2014-12-10 20:31:07
byte b = 10;
Object B= b;
if (B.getClass() == Byte.class) {
System.out.println("Its a Byte");
}注意: Byte是最终的,所以instanceof等同于class。
现在,如果您尝试:
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等等。
https://stackoverflow.com/questions/27400919
复制相似问题