How is it possible that the project compiles in eclipse but javac throws compiler errors?
Working on a group project for a school and the following line throws an error when running javac on the command line.
Object result = engine.eval(equation); //evaluate the arithmetic expression
cellValue = (double) result; // <-- This throws a compiler error (obviously)
But for some reason this compiles and works (!) In eclipse that my bandmates are using. I tried this for myself to confirm, because I couldn't believe it.
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine is a ScriptEngine, if it's relevant at all. I cannot in my entire life figure out how the eclipse compiler allows you to compile a string that passes Object
directly to double
.
source to share
Perhaps your friends are using a different version of the Java language. The Object
to double
(primitive) listing appears to be legal in Java 7, but not in Java 6. You can change your project options in Eclipse or upgrade your compiler to version 7.
Note that casting Object
to double
(class) works in both versions.
source to share
It looks like the allowed conversions have been extended between Java 5 and 7. In the Java Language Specification, 3rd edition (for Java 5 and 6) :
A value of a reference type can be passed to a primitive type by unboxing the conversion (section 5.1.8).
Unboxing conversion converts the values โโof the reference type to the corresponding values โโof the primitive type. Specifically, the following 8 conversions are called unboxing conversions:
- Boolean to boolean
- From type Byte to type byte
- From type Symbol to type char
- From type Short to type short
- From Integer type to int input
- From type Long to type long
- From type Float to type float
- From type Double to type double
So in Java 5 and 6, casting Object
in is double
not legal.
Java Language Specification, Java SE 7 Edition writes:
The following tables list which conversions are used in some caste conversions. Each transformation is indicated by the symbol:
โ means narrowing of the reference transformation (section 5.1.6)
โ stands for unboxing conversion (ยง5.1.8)
and the following table states that casting from object to double value
โ, โ
i.e. cast from Object
to double
is cast to double
, followed by converting unboxing to double
.
So it is very likely that your teammates are compiling for Java 7 and you are compiling for Java 6.
source to share
Allowed caste conversions are detailed in JLS # 5.5 . Specifically, this conversion is allowed:
- narrowing of reference conversion (ยง5.1.6), optionally followed by either unboxing (section 5.1.8) or unchecked conversion (ยง5.1.9)
In your case, if cellValue
is double, drop from is allowed Object
and will try to drop Object
at Double
and then drop Double
before Double
.
source to share