Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java isAssignableFrom Confusion [duplicate]

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?

like image 651
Marty Pitt Avatar asked Feb 07 '26 12:02

Marty Pitt


1 Answers

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.

like image 140
Jon Skeet Avatar answered Feb 09 '26 03:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!