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 referenceT开发者_如何学运维ype = 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.
The javadocs from 1.4 already specify that:
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.
So the behavior of this method was locked in place before auto boxing was introduced, and can't be changed (a new method would have to be introduced).
Given this bug report, it is pretty apparent that not all of the edge cases around the Class object and how auto boxing changes expectations were completely handled.
To answer the second part of your question, the only way I know of to test this case is a series of if statements or some similar resolution mechanism that "boxes" the primitive class type.
精彩评论