Monday, September 5, 2011

Validate Java Expression

    You may come under a scenario where you want to check at runtime if the given expression is valid or not. For example you are building a expression builder on the client side. With the help of of expression builder you can create a expression. Expression may contains different data types like Integer, String and Date. Now the question is how can any one check if the build expression is valid or not. I have the following code that will ensure given expression is valid or not.

Assumption :

1) This code will work on java 6 and above.
2) You have to pass the expression in the form of values.

import java.util.Arrays;
public class ExpressionEvaluator {

public static boolean isValidExpression( String expression) {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.out.println("compiler  = " + compiler);
System.out.println("JAVA HOME = " + System.getProperty("java.home"));
System.out.println("CLASSPATH = " + System.getProperty("java.class.path"));
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class TextExpression {");
out.println("  public static void main(String args[]) {");
out.println("    if(" + expression + "){}");
out.println("  }");
JavaFileObject file = new JavaSourceFromString("TextExpression", writer.toString());
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success =;
return success;

class JavaSourceFromString extends SimpleJavaFileObject {

final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/')+ Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;

No comments:

Post a Comment