Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

java - Looking for an expression evaluator

I'm looking for an evaluator for simple condition expressions. Expressions should include variables (read only), strings, numbers and some basic operators.

E.g. expressions something like this:

${a} == "Peter" && ( ${b} == null || ${c} > 10 )

So far i implemented a rather "magical" parser that returns an AST that i can evaluate, but i can't believe that i'm the first one to solve that problem.

What existing code could i use instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you looked at MVEL? They provide a getting started guide and performance analysis.

Here's one of their simple examples:

// The compiled expression is serializable and can be cached for re-use.
CompiledExpression compiled = MVEL.compileExpression("x * y"); 

Map vars = new HashMap();
vars.put("x", new Integer(5));
vars.put("y", new Integer(10));

// Executes the compiled expression
Integer result = (Integer) MVEL.executeExpression(compiled, vars); 
assert result.intValue() == 50; 

Also (answering my own question) MVEL seems to provide some support for bytecode generation.

Other alternatives, culling from the above answers and my own:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...