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