Cast/boxing/unboxing of numbers Java 9
Paulo Oliveira
paulo.oliveira at ifood.com.br
Mon Mar 26 21:27:35 UTC 2018
Hello,
Testing some nashorn scripts on java 9 I got some unexpected behavior.
The code:
import java.util.Arrays;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Main {
public static void main(String[] args) throws Exception{
ScriptEngine scriptEngine = new
ScriptEngineManager().getEngineByName("Nashorn");
scriptEngine.eval("var imports = new JavaImporter(java.lang.Integer, " +
"java.lang.Long);" +
"var fun1 = function(longs, ints, id) {" +
"with(imports) {" +
"print(id.getId().class);" +
"print(longs.contains(id.getId()));" +
"print(ints.contains(id.getId()));" +
"return Long.valueOf(1);" +
"}" +
"};");
Invocable invocable = (Invocable) scriptEngine;
List<Long> longs = Arrays.asList(1L, 2L);
List<Integer> ints = Arrays.asList(1, 2);
Teste teste = new Teste(1L);
Object result = invocable.invokeFunction("fun1", longs, ints, teste);
System.out.println(result.getClass());
}
}
public class Teste {
private Long id;
public Teste(Long id) {
this.id =id;
}
public Long getId() {
return id;
}
}
Executing the code
It produces:
Java 8.161
class java.lang.Long
true
false
class java.lang.Long
Java 9.0.4 and 10
class java.lang.Long
false
true
class java.lang.Integer
Nashorn is changing every number that fits a Integer in Integers, even if I
explicit define as Long.
This causes a problem on List.contains, because it receives a Object, if I
try to verify if a long exists in a list of longs, it returns false.
Is it a expected behavior ?
--
*Paulo Oliveira*
*Desenvolvedor BackEnd*
*TEL:* +55 (11) 3634-3378
www.ifood.com.br
<https://itunes.apple.com/br/app/ifood-delivery-e-entrega-comida/id483017239?mt=8>
<https://play.google.com/store/apps/details?id=br.com.brainweb.ifood>
<https://www.facebook.com/iFood?fref=ts> <https://twitter.com/iFood>
More information about the nashorn-dev
mailing list