Java Scripting API -- Property from JavaScript object is always null

144 views Asked by At

Below is the code I am running in my Java compiler:

ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");

engine.put("person", "{name: 'Bob', favoriteColor: 'red'}");
System.out.println(engine.get("person.name"));

I would expect this to evaluate to "Bob", but instead it gives me null. If I try printing just the user object, it properly gives me this output:

{name: 'Bob', favoriteColor: 'red'}

Why is person.nameevaluating to null? Any help would be appreciated!

1

There are 1 answers

0
neuronaut On BEST ANSWER

Apparently the put method doesn't evaluate the value passed, but assumes it is meant as a literal. For example script.put("test", 5) will put the literal integer value 5 into a variable called test.

The second thing that's wrong is that get also doesn't evaluate its parameter, but assumes it, too, is the literal name of the variable.

However, it is possible to do what you are trying to accomplish. Try this:

engine.eval ("var person = {name: 'Bob', favoriteColor: 'red'}");
System.out.println(((Bindings) engine.get("person")).get ("name"));