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.

2
  • 4
    So you're looking for a REPL like JShell? Commented Sep 19, 2017 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. Commented Sep 19, 2017 at 17:35

2 Answers 2

2

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

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

Sign up to request clarification or add additional context in comments.

6 Comments

It feels like BeanShell is out of date, isn't it?
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.
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?
docs.oracle.com/javase/8/docs/technotes/guides/scripting/… ...there are several engines, while one can create custom engines. at least there's importPackage() & importClass().
|
1

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

1 Comment

exp4j seems to be like the mentioned expression languages but I really need scripting with short code blocks, multiple statements etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.