开发者

Custom interpreter in java

开发者 https://www.devze.com 2023-03-07 23:33 出处:网络
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 th

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 开发者_如何学Goto write by myself?

Thanks


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')");
    }
}


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.


What you need is called "scripting engine". Quick search reveals Rhino. This is a good option cause it's JavaScript, and many people know JavaScript and there exists a certain amount of third-party extensions (libraries and code snippets) for it.


You could use ANTLR, but you will have to define a grammar (the parser will be generated for you).

Check this expression elevator example, it is similar to your problem, but instead of reading files it reads from the standard input.

If you choose ANTLR, take I look at ANTLRWorks, it is a GUI that will help with ANTLR development (I think it is also available as an Eclipse plugin).


I know this an old thread, but some time ago I've implemented a small interpreter for language similar with JavaScript (with more restrictions), the code is published in Github at https://github.com/guilhermelabigalini/interpreter

But it does support IF/CASE/LOOPS/FUNCTIONs, see below:

function factorial(n) {
  if (n == 1) 
    return 1;

   return n * factorial(n - 1);
}

var x = factorial(6);  
0

精彩评论

暂无评论...
验证码 换一张
取 消