is there a way to check instanceof primitives variables java

前端 未结 3 867
小鲜肉
小鲜肉 2020-12-16 03:40

We can know object reference is-a test by using instanceof operator. But is there any operator to check primitive types. For example:

byte b = 10;

3条回答
  •  时光取名叫无心
    2020-12-16 04:13

    byte b = 10;
    Object B= b;
     if (B.getClass() == Byte.class) {
      System.out.println("Its a Byte");
     }
    

    Note: Byte is final, so instanceof is equivalent to class equality.

    Now if you try:

    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
    

    etc...

提交回复
热议问题