Spring expression return type

176 views Asked by At

I need a way to figure out if a supplied Spring Expression can evaluate to boolean or not. For example, an expression like "age == 18" can return a Boolean in SpEL, but not something like "age + 10". Please note that I would only have the expression at hand while doing this validation (and hence, I cannot just evaluate expression and see return type)

1

There are 1 answers

0
Jihed Amine On

Using JavaCompiler, you could compile in memory the expression as in this example and get the evaluated result.

Your in-memory compiled method could do something like (your expression being the String variable theExpressionToEvaluate)

StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println("  public static void isBoolean() {");
out.println("try {boolean result = " + theExpressionToEvaluate + "; return result;}");
out.println("catch (ClassCastException e) { return false; }");