user468311
user468311

Reputation:

Creating meta language with Java

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?

Upvotes: 0

Views: 4670

Answers (5)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340763

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.

Upvotes: 8

Ishtar
Ishtar

Reputation: 11662

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

Upvotes: 5

KarlP
KarlP

Reputation: 5181

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

Upvotes: 1

Edwin Buck
Edwin Buck

Reputation: 70909

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.

Upvotes: 1

Jesper
Jesper

Reputation: 206856

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.

Upvotes: 1

Related Questions