Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

is there a way to check instanceof primitives variables java

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;

Now if I only consider the value 10. Is there any way I could find out that it was declared as a byte?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Local variables

Assuming you mean by local variables the primitive will always be automatically wrapped by its wrapper type whenever passed as an object, java.lang.Byte in this case. It's impossible to refer to local variables using reflection so you cannot differentiate between Byte and byte or Integer and int etc.

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()));

Fields

However, if you're talking about fields in classes, then things are different as you can get a handle on actual declared type. You can then use java.lang.Class.isPrimitive() as expected and the type will be 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());
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...