0

I've using the java ScriptEngine to execute a script that could alter a shared Java class. I'm wondering, if it's possible to support dynamically created variables in the java class?

// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();

// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript"); 
engine.put("javaclass", jClass);

engine.eval("javaclass.propertyThatDoesNotExist = 'test'"); // throws exception
webber
  • 1,523
  • 4
  • 21
  • 46

2 Answers2

1

You can register a javascript variable in the engine, by using the ScriptEngine#put(String key, Object value) method. For example:

engine.put("i", 10);

This is how can you retrieve the registered variable:

int i = ((Double) engine.eval("i")).intValue();
System.out.println("JavaScript variable in Java; i = " + i);
Konstantin Yovkov
  • 59,030
  • 8
  • 92
  • 140
0

Java is not a dynamic language. So you can not add a property/variable to that class/object. For that you need to use a different language like Groovy or Java Script.

Angel O'Sphere
  • 2,427
  • 16
  • 16
  • I tried the same code with groovy and it failed too with the same error (no public property). I used this post http://stackoverflow.com/a/6569565/1228906 and I was able to dynamically create properties in scripts but doing the same in the ScriptEngine fails. Thanks though! – webber Oct 04 '13 at 20:12
  • I assume you used the "binding". You an not add a "property" to a "class" dynamicaly. You only can define dynamic global variables. – Angel O'Sphere Nov 12 '13 at 16:21