001 package groovy.util;
002
003 import org.codehaus.groovy.control.CompilationFailedException;
004
005 import groovy.lang.Binding;
006 import groovy.lang.GroovyShell;
007
008 /**
009 * Allow easy integration from Groovy into Java through convenience methods.
010 * @see EvalTest
011 * @author Dierk Koenig
012 */
013
014 public class Eval {
015 /**
016 * @param expression the Groovy expression to evaluate
017 * @return the result of the expression
018 * @throws CompilationFailedException if expression is no proper Groovy
019 */
020 public static Object me(final String expression) throws CompilationFailedException {
021 return me(null, null, expression);
022 }
023
024 /**
025 * evaluate expression and make object available inside the expression as 'symbol'
026 * @param expression the Groovy expression to evaluate
027 * @return the result of the expression
028 * @throws CompilationFailedException if expression is no proper Groovy
029 */
030 public static Object me(final String symbol, final Object object, final String expression) throws CompilationFailedException {
031 Binding b = new Binding();
032 b.setVariable(symbol, object);
033 GroovyShell sh = new GroovyShell(b);
034 return sh.evaluate(expression);
035 }
036
037 /**
038 * evaluate expression and make x available inside the expression as 'x'
039 * @param expression the Groovy expression to evaluate
040 * @return the result of the expression
041 * @throws CompilationFailedException if expression is no proper Groovy
042 */
043 public static Object x(final Object x, final String expression) throws CompilationFailedException {
044 return me("x", x, expression);
045 }
046
047 /**
048 * evaluate expression and make x and y available inside the expression as 'x' and 'y'
049 * @param expression the Groovy expression to evaluate
050 * @return the result of the expression
051 * @throws CompilationFailedException if expression is no proper Groovy
052 */
053 public static Object xy(final Object x, final Object y, final String expression) throws CompilationFailedException {
054 Binding b = new Binding();
055 b.setVariable("x", x);
056 b.setVariable("y", y);
057 GroovyShell sh = new GroovyShell(b);
058 return sh.evaluate(expression);
059 }
060
061 /**
062 * evaluate expression and make x,y,z available inside the expression as 'x','y','z'
063 * @param expression the Groovy expression to evaluate
064 * @return the result of the expression
065 * @throws CompilationFailedException if expression is no proper Groovy
066 */
067 public static Object xyz(final Object x, final Object y, final Object z, final String expression) throws CompilationFailedException {
068 Binding b = new Binding();
069 b.setVariable("x", x);
070 b.setVariable("y", y);
071 b.setVariable("z", z);
072 GroovyShell sh = new GroovyShell(b);
073 return sh.evaluate(expression);
074 }
075 }