开发者

Parse JavaScript-like syntax to my own Java Methods

Basically I want to be able to do be able to parse a JavaScript-like syntax. For example:

var results = system.function('example');  

if(results == "h开发者_C百科ello") {  
   console_print("ding dong.");  
}  

So basically you get it, results will be a "string" and system.function will call a Java method, and those results will go into the results string.

I want to be able to do basic math, and validation in this as well, but I want this done in Java. Any ideas?


If you're willing to use JavaScript (not just JavaScript-like), and you're using Java 1.6+, then you can use the Scripting API:

import javax.script.*;

public class Main {

  public static void main (String[] args) throws Exception {

    String source =
        "var system = new Array();                       \n" +
        "system['foo'] = function(s) { return 'hello'; } \n" +
        "                                                \n" +
        "var results = system.foo('example');            \n" +
        "                                                \n" +
        "if(results == \"hello\") {                      \n" +
        "  print(\"ding dong.\");                        \n" +
        "}                                               \n";

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    engine.eval(source);
  }
}

which will print:

ding dong.

to the console.

And to invoke Java methods from the scripting language, you could give BeanShell a try:

package test;

import bsh.Interpreter;

public class Main {

  public static void foo(Object param) {
    System.out.println("From Java, param=" + param);
  }

  public static void main (String[] args) throws Exception {

    Interpreter i = new Interpreter();
    i.eval("a = 3 * 5; test.Main.foo(a);");
  }
}

which will print:

From Java, param=15

The core interpreter JAR of BeanShell is only 143 KB: more lightweight than that will be difficult, IMO.


I think you can use Rhino for this. Rhino is an javascript engine that can be embedded in java.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜