首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法检查instanceof原语变量

有没有办法检查instanceof原语变量
EN

Stack Overflow用户
提问于 2014-12-10 20:22:59
回答 3查看 18.5K关注 0票数 10

通过使用instanceof操作符,我们可以知道对象引用是一个测试。但是,是否有任何操作符来检查基元类型。例如:

代码语言:javascript
复制
byte b = 10;

现在,如果我只考虑值10。有没有办法让我知道它是被声明为字节的?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-12-10 20:25:37

局部变量

假设您所说的局部变量,无论何时作为对象传递时,原语都将自动由其包装器类型包装,在本例中为java.lang.Byte。使用反射来引用局部变量是不可能的,所以你不能区分Byte和byte,或者Integer和int等等。

代码语言:javascript
复制
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。

代码语言:javascript
复制
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());
    }

}
票数 7
EN

Stack Overflow用户

发布于 2014-12-10 21:56:13

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

代码语言:javascript
复制
    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");            
    }
票数 4
EN

Stack Overflow用户

发布于 2014-12-10 20:31:07

代码语言:javascript
复制
byte b = 10;
Object B= b;
 if (B.getClass() == Byte.class) {
  System.out.println("Its a Byte");
 }

注意: Byte是最终的,所以instanceof等同于class。

现在,如果您尝试:

代码语言:javascript
复制
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

等等。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27400919

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档