Inconsistent missing property handling with java objects

Mike Rettig mike.rettig at gmail.com
Wed Sep 3 14:13:11 UTC 2014


With nashorn, it seems that the assignment and accessing of missing
properties on java objects is handled as 'undefined'.

Example:

        String engine = "nashorn";
        ScriptEngineManager engineManager =
                new ScriptEngineManager();
        final ScriptEngine nashorn = engineManager.getEngineByName(engine);
        nashorn.eval("var d=new java.util.Date();");
        nashorn.eval("d.badProp=1233");
        nashorn.eval("print(d.badProp)");


This will print 'undefined'. It doesn't fail on the 'badProp' on the Date
object. With Rhino, this would fail on the assignment of the bad property
with the following error:

"Exception in thread "main" javax.script.ScriptException:
sun.org.mozilla.javascript.internal.EvaluatorException: Java class
"java.util.Date" has no public instance field or method named "badProp".
(<Unknown source>#1) in <Unknown source> at line number 1"

I want the script to fail when the bad property is referenced.  I've tried
'use strict', the rhino compatibility script, and attempting to define
__noSuchProperty__
on the java object. I can create a wrapper object that simply delegates to
the java object and throws if a property is undefined, but that seems
excessive.

Is this the correct behavior? Is there a way to work around this behavior
in nashorn?

Thanks,

Mike


More information about the nashorn-dev mailing list