Creating meta language with Java

前端 未结 5 1466
清歌不尽
清歌不尽 2020-12-04 04:13

guys! I need to create some sort of meta language which I could embed in XML and then parse with Java. For example:


    [if value1>value2 the         


        
相关标签:
5条回答
  • 2020-12-04 04:28

    It is almost certain that a homemade language would suck, especially in the long run, so don't roll something on your own.

    There are several jsp-like frameworks available, maybe one of those would do the trick:

    JSTL/JSP EL (Expression Language) in a non JSP (standalone) context

    0 讨论(0)
  • 2020-12-04 04:30

    A user here, Bart Kiers. Wrote a tutorial about creating a simple language in Java with ANTLR.

    0 讨论(0)
  • 2020-12-04 04:40

    If you really want to develop your own language, start off with the interpreter pattern. If you just want to leverage somebody else's language in your Java code, look to integration ala JSP style embedded languages.

    0 讨论(0)
  • 2020-12-04 04:41

    Java has a scripting API that you could use for this. Lookup the API documentation of the package javax.script.

    You could include code in for example JavaScript in the code element, and execute that using the scripting API.

    0 讨论(0)
  • 2020-12-04 04:47

    Java has a built-in JavaScript interpreter:

    ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    jsEngine.put("value1", 8);
    jsEngine.put("value2", 9);
    String script = "if(value1 + 2 > value2) {'Foo'} else {'Bar'}";
    final Object result = jsEngine.eval(script);
    System.out.println(result);  //yields "Foo" String
    

    Of course you are free to both load the script from anywhere you need and to provide it with any context (value and value2 in this example) you want.

    See also Scripting for the Java Platform article.

    0 讨论(0)
提交回复
热议问题