Can't call hasOwnProperty on Java list using Nashorn

I have an application that runs many javascript servers and I am trying to convert from Rhino to Nashorn but I am having problems with my scripts. Using Rhino, I will always convert whatever arguments I had for the function to a JSON string, but this is very slow. With Nashorn, I'm trying to just pass the arguments as Java objects, but they don't seem to inherit functions from the Javascript type. Here is a sample method that illustrates my problem when hasOwnProperty is not available in my array:

public String printArrayValues() throws ScriptException, NoSuchMethodException {

  String script =
      "function printArrayValues(objArray) {\n" +
      "  var result = '';\n" +
      "  for(var obj in objArray) {\n" +
      "    if(objArray.hasOwnProperty(obj)) {\n" +
      "      result = result + ' ' + objArray[obj];\n" +
      "    }\n" +
      "  }\n" +
      "  return result;\n" +
      "}";

  List<String> data = Arrays.asList(new String[]{ "one", "two", "three"});

  ScriptEngine scriptEngine = new NashornScriptEngineFactory().getScriptEngine();
  scriptEngine.eval(script);
  String result = (String) ((Invocable) scriptEngine).invokeFunction("printArrayValues", data);
}

      

Here, calling invokeFunction throws an exception:

javax.script.ScriptException: TypeError: [one, two, three] has no such function "hasOwnProperty" in <eval> at line number 4

      

If I call the same function in the browser, I get what I expect:

> printArrayValues(["one", "two", "three"]);
> " one two three"

      

Is there a way that I can do this so I can actually use these Java objects without turning them into a JSON string and then evaluating it into a Javascript object?

+3


source to share


2 answers


You cannot use Java arrays this way. Java arrays are "hard" objects. Unlike ordinary objects, they have no methods and they support an operator []

that objects cannot.



This article is about Nashorn at Oracle explains that you need to use the methods Java.to

and Java.from

in your javascript, to change the Java array into an array of Javascript.

+2


source


use Java.from()

to convert Java List

to Javascript Array

and then work with it.



  String script =
  "function printArrayValues(objArray) {\n" +
  "  var result = '';\n var temp = Java.from(objArray);" +
  "  for(var obj in temp ) {\n" +
  "    if(temp .hasOwnProperty(obj)) {\n" +
  "      result = result + ' ' + temp [obj];\n" +
  "    }\n" +
  "  }\n" +
  "  return result;\n" +
  "}";

      

+2


source







All Articles