reflecting on JS functions/objects

A. Sundararajan sundararajan.athijegannathan at oracle.com
Sun Oct 20 23:31:04 PDT 2013


Bindings jsglobals = e.getContext().getBindings(ScriptContext.ENGINE_SCOPE);

You can iterate key-value pairs of the Bindings.  For script objects and 
functions, the value is of type 
jdk.nashorn.api.scripting.ScriptObjectMirror.
After checking instanceof on the value, you can call 
ScriptObjectMirror.isFunction() to check if that is a function or not.

Essentially, you can work with javax.script API and 
jdk.nashorn.api.scripting API to get these. ScriptObjectMirror has 
methods to get/set properties and call methods, constructors etc. When 
you have a function, you can call get("name") on it to get "name" 
property of that Function object.

Hope this helps,
-Sundar

On Saturday 19 October 2013 06:08 AM, Michael Roberts wrote:
> Just to be clear, previously, with Rhino, I could do something like:
>
> DebuggableScript deb = Context.getDebuggableView(script);
> int functionCount = deb.getFunctionCount();
>
> // Build a collection of all of the implemented functions in the JS
> implementation
> HashSet<String> functionNames = new HashSet<String>();
>
> for (int i = 0; i < functionCount; i++) {
> DebuggableScript function = deb.getFunction(i);
> String functionName = function.getFunctionName();
> functionNames.add(functionName);
> }
>
> Looking for a rough analog.  I assume it's in the ScriptContext somwhere?
>
> M
>
>
> On Fri, Oct 18, 2013 at 3:30 PM, Michael Roberts <mike at 7f.com> wrote:
>
>> Hi, I am looking at Nashorn for the first time and have a lightweight
>> question.
>>
>> One thing which springs immediately to mind is the need to reflect on the
>> contents of a js script.  I.e., I might do something trivial like :
>>
>> ScriptEngine e = (new ScriptEngineManager).getEngineByName("nashorn");
>> e.eval("function foo() { return -1; }; function foo2() { return 0; }");
>>
>> I'd then like to enumerate through the functions the script defined so I
>> can create an external binding to them, without knowing beforehand that my
>> script contains foo and foo2, as the examples I have seen do.  Does this
>> exist currently and if so, where should I be looking?
>>
>> best regards
>>
>> M
>>
>>
>>



More information about the nashorn-dev mailing list