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.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler.CompilationTask;
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("  }");
out.println("}");
out.close();
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 = task.call();
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;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}

No comments:

Post a Comment