Java Scripting API - JavaScript object property is always null

Below is the code that I run 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 expect it to be rated as "Bob", but instead it gives me null. If I try to print only the user object, it will correctly give me this result:

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

Why person.nameis it rated as null? Any help would be appreciated!

+4
source share
1 answer

Apparently, the method putdoes not evaluate the passed value, but assumes that it is intended as a literal. For example, script.put("test", 5)it places the value of a literal value 5in a variable with a name test.

, , , get , , .

, . :

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

All Articles