有没有一种方法来检查instanceof基本变量java

Mat*_*een 7 java variables primitive-types

我们可以知道对象引用是-通过使用instanceof运算符进行的测试。但是是否有任何运算符可以检查基本类型。例如:

byte b = 10;
Run Code Online (Sandbox Code Playgroud)

现在,如果我仅考虑价值10。我有什么办法可以发现它被声明为字节?

Ada*_*dam 6

局部变量

假设您是用局部变量来表示的,则当作为对象传递时,原语将始终按其包装器类型自动包装,在这种情况下为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()));
Run Code Online (Sandbox Code Playgroud)

领域

但是,如果您谈论的是类中的字段,那么情况会有所不同,因为您可以获取实际声明的类型的句柄。然后,可以按预期使用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());
    }

}
Run Code Online (Sandbox Code Playgroud)


Gre*_*ren 5

如果你真的想玩文字游戏......

    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");            
    }
Run Code Online (Sandbox Code Playgroud)