小编典典
如果你使用的是Java 6,则可以尝试使用Java Compiler API。其核心是JavaCompiler类。你应该能够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 {" +
" 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 options = null;
Iterable 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。
2020-03-02