1

I am aware of the Java Scripting API (which runs scripts written in JavaScript, Groovy etc) and several expression languages (SpEL, JEXL, JUL). But it is possible to write scripts in Java itself and then invoke that script from Java code?

I found some information on compiling Java programmatically via the tools API but this not like scripting (i.e. the context is different).

I imagine something like this script being executed by my Java code:

int i = 42 + getFoo();
setBar(i);

Now - when invoked with a context that provides getFoo and setBar methods - it should evaluate i and call the method.

Steffen Harbich
  • 2,639
  • 2
  • 37
  • 71
  • 4
    So you're looking for a REPL like JShell? – Vince Sep 19 '17 at 14:45
  • JSell could be an option for Java 9 but I'm fixed on Java 8. The alternative BeanShell feels outdated (from 2005?). As long as JShell scripts can be called from Java it would serve my need. – Steffen Harbich Sep 19 '17 at 17:35

2 Answers2

2

Try BeanShell or the Compiler API or javax.script ...

one either has to interpret the text input or compile to byte-code, somehow.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
  • https://code.google.com/archive/p/beanshell2/ & https://github.com/pejobo/beanshell2 – Martin Zeitler Sep 19 '17 at 14:59
  • It feels like BeanShell is out of date, isn't it? – Steffen Harbich Sep 19 '17 at 17:46
  • see the link for beanshell2... javax.script might be the suggested method, while it can interpret Java code. it depends what that file might contain - because writing a simple parser should be no problem. – Martin Zeitler Sep 19 '17 at 17:48
  • Ok, I wonder how I can interpret Java code with javax.script? As far as I know JavaScript, Groovy etc are available but I didn't read that Java syntax itself is supported. Do you know how it works? – Steffen Harbich Sep 19 '17 at 17:50
  • https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html ...there are several engines, while one can create custom engines. at least there's `importPackage()` & `importClass()`. – Martin Zeitler Sep 20 '17 at 02:47
  • based upon the input below, I have found the `Expression Language 3.0 specification, JSR341` - see `javax.el` https://github.com/javaee/el-spec/tree/master/api/src/main/java/javax/el and `commons-jexl` http://commons.apache.org/proper/commons-jexl/ ... which both seem to be leaning towards enabling the web-scripting. – Martin Zeitler Sep 28 '17 at 00:00
1

Consider using exp4j's nice API. Also check out other options at https://stackoverflow.com/a/41532702/37020

orip
  • 73,323
  • 21
  • 116
  • 148
  • exp4j seems to be like the mentioned expression languages but I really need scripting with short code blocks, multiple statements etc. – Steffen Harbich Sep 19 '17 at 17:52