Get array as result of ScriptEngine.eval()

Viewed 1386

I'm trying to use javax.script.ScriptEngine to eval() some JS scripts. How can I know if the result after eval() which is of type Object is an array? And if so, how can I cast it?

Right now, to know if the object is of type Number or of type String i use instanceof. And when the result of the script is an array, if I print with System.out.println() the object returned it simply prints [object Array].

4 Answers

In my case modifying the script to make it return list does the trick:

private String arrayToList() {
    if (javascript.startsWith("[") && javascript.endsWith("]"))
        javascript = "java.util.Arrays.asList(" + javascript + ")";
    return javascript;
}

But of course it handles only the case where array results from using brackets, for example:

["entry1", "entry2", settings.getMainUserEmail(), loginEmail]

Anyway the bottom line is that you need to return a List instead of array. Then you can also use instanceof.

final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
scriptEngine.eval("count = ['one', 'two', 'three'];");
scriptEngine.eval("className = count.constructor.name;");

final String className =  (String) scriptEngine.get("className");

switch(className) {

case "Array":
    scriptEngine.eval("json= JSON.stringify(count);");
    final String json =  (String) scriptEngine.get("json");

    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    final String[] readValue = mapper.readValue(json, String[].class);
    break;

case "Number":
    ...
}
Related