a colleague checked in code:
number n = ...; double nr = n == null ? 0.0 : (double) n;
another colleague complained didn't compile, , that's expect. however, turned out had pulled code svn , worked fine. had our java version set 1.7 in eclipse, , turned out code compiles fine under eclipse 4.4.2 (luna) fails under 4.2.2.
i fixed issue replacing cast n.doublevalue()
.
now actual question is: why accepted in first place? should of course work when casting double
instead of double
, i'd think direct cast number
double
disallowed. so, bug in eclipse 4.2.2 fixed in meantime, or eclipse 4.4.2 silently accept code should not compile (which imho bug)?
with java 7, casting system had changed regards primitive types in order allow working methodhandle
s. when invoking method handle, javac compiler generates so-called polymorhic signature derives method handle's method signatures. these polymorphic signatures created hinting out parameter's type casting. example, when binding method signature of double, long -> int
, following casting required:
number foo = 42d, bar = 43l; int ignored = (int) methodhandle.invoke((double) object, (long) bar);
the source code signature of methodhandle::invoke
defined object[] -> object
, without directly casting value primitive type, polymorphic signature not generated.
obviously, possible, java compiler had changed allow such castings not legal. while - in theory - possible restrict use of castings methods annotated @polymorhicsignature
, have resulted in strange exception why possible in javac appropriate byte code generated when not creating polymorphic signature. yet, primitive types still represent own runtime types pointed out in other answer posted generated byte code of such casting outside of methodhandle
object foo = 42; int.class.cast(foo);
would result in runtime exception.
however, agree comments not dicussed appropriately in jls found thread mentioning specification gap. mentioned specification should updated accordingly once lambda expressions put in place jls java 8 not seem mention such castings or @polymorphicsignature
either. @ same time, states [a]ny conversion not explicitly allowed forbidden.
arguably, jls lagging behind javac implementation , eclipse compiler has surely not picked properly. compare corner-cases of generic type inference several ide compiler behave differently javac until today.
Comments
Post a Comment