Why this is a compile-time error when Java does the Autoboxing? Am I missing something?
int primitiveIntVariable = 0;
if (primitiveIntVariable instanceof Integer) {
}
I get
Inconvertible types; cannot cast 'int' to 'java.lang.Integer'
As the name suggests, instanceof means an instance (object) of a class. Primitive datatypes are not instances.
This is how you get the class for a primitive datatype:
int i = 1;
System.out.println(((Object)i).getClass().getName());
// prints: java.lang.Integer
So instead of instanceof, use isInstance(...) like this:
Integer.class.isInstance(1); // returns true
Integer.class.isInstance(1.2); // returns false
Hope this helps. Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With