I'd like to get a better understanding of the isAssignableFrom behaviour in Java between primitive and reference types.
Eg:
System.out.println(boolean.class.isAssignableFrom(Boolean.class)); // false
System.out.println(Boolean.class.isAssignableFrom(boolean.class)); // false
boolean primitive;
Boolean referenceType = true;
primitive = referenceType;
System.out.println(primitive); // true
I know that when assigning primitives <-> reference that boxing / unboxing occurs as required, but I'd have thought that therefore isAssignableFrom would return true in the first two examples above.
Could someone please explain why it returns false, and what the appropriate test here is?
You can't actually assign a boolean value to a Boolean variable - but you can convert from boolean to Boolean using auto-boxing.
The JavaDocs make the rules pretty clear:
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.
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