r/javahelp • • Dec 20 '22

Unsolved Scripting language for Java

hello

i have to give my users ability to modify their data via simple code snippets. sometimes its simple math expressions ("price * 1.5" etc) sometimes they split strings, extract data from json etc. this gives my platform a lot of flexibility.

i want to use a fast scripting language in java. i tried graal.js with scriptenginemanager but it takes too long to boot up.

is there any faster alternatives or other approaches ? i am asking this because i just started using java and if there is a better solution in java ecosystem i dont want to miss it

thank everyone in advance for any help :)

16 Upvotes

23 comments sorted by

View all comments

1

u/sometimes_insightful Dec 21 '22 edited Dec 21 '22

Depending on how complex your expressions are, you might consider using something like antlr and writing your own parser for it. Setting up something to handle math and string operations wouldn’t be very hard and then you can control the syntax however you like. You can use a visitor and visit each node in the syntax tree and return the result of each sub-expression.

Another benefit is this makes security much easier. If you are running a scripting engine you need to keep in mind that people can try to write malicious expressions. Something simple as an infinite loop can hang your process, not to mention worse attacks that could escape the sandbox.

Here is an example grammar for arithmetic you could try out, but keep in mind you can make it do pretty much anything.

https://github.com/antlr/grammars-v4/blob/master/arithmetic/arithmetic.g4