0

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

<code>
    [if value1>value2 then "Hello, Bob!" else "Hello, Jack"]
</code>

or

 <code>
     [if value1+2>value2 return true]
 </code>

I need to implement conditional statements,arithmetics.

Any suggestions where should I start looking?

  • Java is not really the language for something like this. If you must use the JVM, try a Clojure, as Lisp makes this stuff easy. – Mike Sep 27 '11 at 20:20
  • 1
    @Mike Lisp makes ANYTHING easy? ;-) – MaDa Sep 27 '11 at 21:48
  • I am starting to wonder about what you are trying to solve here... Neither writing dynamic content in XML nor parsing XML while reacting on he contents does require scripting... Or does it? – KarlP Sep 27 '11 at 22:19
  • can anyone please say that what the meta language and object language in this code are? –  Oct 23 '14 at 18:33

5 Answers5

8

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
5

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

Community
  • 1
  • 1
Ishtar
  • 11,542
  • 1
  • 25
  • 31
1

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.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

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.

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
1

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

Community
  • 1
  • 1
KarlP
  • 5,149
  • 2
  • 28
  • 41
  • 2
    Don't kick the guy in the crotch. Such language would not necessarily "suck", only a naively implemented parser would. – MaDa Sep 27 '11 at 21:52
  • I'm not kicking anyone, just drawing my conclusions from observations made... It will not *necessarily* suck, it's just very likely that it will end up that way... :-) – KarlP Sep 27 '11 at 22:14