Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom interpreter in java

Hi
I want to write a program to be able to parse & execute some files
The file consists of some custom commands (I want to be able to define commands and appropriate methods so when program see that command it should execute the appropriate method)
It's grammar is not important for me; I just want to be able to define commands
Something like a simple and small interpreter written in java.
Is there any library for this purpose?
Or I need to write by myself?

Thanks

like image 499
Ariyan Avatar asked Feb 25 '23 03:02

Ariyan


2 Answers

Java 6 (and newer) have this in the standard library: have a look at the API documentation of the package javax.script. You can use this to run scripts from your Java program (for example to automate your program) using any scripting language for which there is a plug-in engine available for the javax.script API. By default, support for JavaScript is supplied.

See the Java Scripting Programmer's Guide.

Simple example from that guide:

import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("print('Hello, World')");
    }
}
like image 52
Jesper Avatar answered Mar 08 '23 11:03

Jesper


Have you considered looking at BeanShell?

Provides for having Java-like snippets interpreted at runtime.

If you need a bit more than that, then consider embedding e.g. JPython or another small interpreter. Just choose one that is JSR-233 compliant to get generic debugging support.

like image 40
Thorbjørn Ravn Andersen Avatar answered Mar 08 '23 12:03

Thorbjørn Ravn Andersen