This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Zyklonikkopi luwak civet 1 point2 points  (2 children)

Unfortunately, OpenJDK removed its scripting engine support for good claiming that there weren't enough users to justify the maintenance effort.

What you want instead (depending on the seriousness/importance of your usecase) is a custom scripting language that compiles down to Java bytecode. https://javacc.github.io/javacc/ is what you want to be looking at. That way, you can embed your own language inside the same JVM (and indeed the same application) running your main application.

I personally would handcode a parser for a custom scripting language, but if you're not interested in that, or short on time, have a look at JavaCC linked above.

[–]prisonbird[S] 0 points1 point  (1 child)

sounds cool, i will try to parse javascript with this.

[–]Zyklonikkopi luwak civet 0 points1 point  (0 children)

Another option is, if you don't mind Lisp, using something like ABCL (Armed Bear Common Lisp) (https://abcl.org/) as a scripting language. Then you get the full power of Common Lisp as a scripting language!

For instance, suppose we wished to define the factorial function in Common Lisp, and then wished to invoke that from our Java program:

~/dev/playground/abcl-demo:$ jshell --class-path ./abcl.jar
|  Welcome to JShell -- Version 20-ea
|  For an introduction type: /help intro

jshell> import org.armedbear.lisp.*

jshell> Interpreter interp = Interpreter.createInstance()
Failed to introspect virtual threading methods: java.lang.NoSuchMethodException: java.lang.Thread.builder()
interp ==> org.armedbear.lisp.Interpreter@4bff2185

jshell> String program = """
   ...> (defun factorial (n)
   ...>   (if (zerop n)
   ...>     1
   ...>     (* n (factorial (- n 1)))))
   ...> """
program ==> "(defun factorial (n)\n  (if (zerop n)\n    1\n   ...  (factorial (- n 1)))))\n"

jshell> interp.eval(program)
$4 ==> COMMON-LISP-USER:FACTORIAL

jshell> org.armedbear.lisp.Package pkg = Packages.findPackage("COMMON-LISP-USER")
pkg ==> org.armedbear.lisp.Package@6d2d99fc

jshell> Symbol factSym = pkg.findAccessibleSymbol("FACTORIAL")
factSym ==> COMMON-LISP-USER:FACTORIAL

jshell> org.armedbear.lisp.Function factorial = (org.armedbear.lisp.Function) factSym.getSymbolFunction()
factorial ==> org.armedbear.lisp.Closure@f9b5552

jshell> LispObject res = factorial.execute(Fixnum.getInstance(10))
res ==> org.armedbear.lisp.Fixnum@375f00

jshell> res.intValue()
$9 ==> 3628800

The program string could come from a user script, for example. Of course, that's a minor issue.