Java中的自定义解释器 [英] Custom interpreter in java

查看:164
本文介绍了Java中的自定义解释器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我想编写一个程序来解析&执行一些文件
该文件包含一些自定义命令(我希望能够定义命令和适当的方法,因此当程序看到该命令时,它应该执行适当的方法)
语法对我来说并不重要;我只想能够定义命令
类似用Ja​​va编写的简单而小型的解释器.
是否有用于此目的的任何库?
还是我需要自己写?

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?

谢谢

推荐答案

Java 6(及更高版本)在标准库中具有此功能:请查看软件包javax.script的API文档.您可以使用它来使用任何脚本语言从Java程序运行Java脚本(例如,使程序自动化),该脚本语言具有javax.script API可用的插件引擎.默认情况下,提供对JavaScript的支持.

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.

请参见《 Java Scripting程序员指南》 .

该指南中的简单示例:

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

这篇关于Java中的自定义解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆