我想知道是否有任何方法可以将A转换String为Java可编译代码。
String
我有一个比较表达式保存在数据库字段中。我想从数据库中检索它,然后在条件结构中对其求值。
有什么办法吗?
如果你使用的是Java 6,则可以尝试使用Java Compiler API。其核心是JavaCompiler类。你应该能够Comparator在内存中构造对象的源代码。
Comparator
警告:由于某些奇怪的原因,我的平台上不存在JavaCompiler对象,因此我实际上并未尝试下面的代码…
警告:编译任意Java代码可能会危害你的健康。
考虑一下自己被警告…
String comparableClassName = ...; // the class name of the objects you wish to compare String comparatorClassName = ...; // something random to avoid class name conflicts String source = "public class " + comparatorClassName + " implements Comparable<" + comparableClassName + "> {" + " public int compare(" + comparableClassName + " a, " + comparableClassName + " b) {" + " return " + expression + ";" + " }" + "}"; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); /* * Please refer to the JavaCompiler JavaDoc page for examples of the following objects (most of which can remain null) */ Writer out = null; JavaFileManager fileManager = null; DiagnosticListener<? super JavaFileObject> diagnosticListener = null; Iterable<String> options = null; Iterable<String> classes = null; Iterable<? extends JavaFileObject> compilationUnits = new ArrayList<? extends JavaFileObject>(); compilationUnits.add( new SimpleJavaFileObject() { // See the JavaDoc page for more details on loading the source String } ); compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits).call(); Comparator comparator = (Comparator) Class.forName(comparableClassName).newInstance();
之后,你只需要在数据库字段中存储适当的Java表达式,a并引用和即可b。
a