将字符串转换为代码 [英] Convert String to Code

查看:92
本文介绍了将字符串转换为代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方法可以将 String 转换为Java可编译代码。

I want to know if there is any way to convert a String to Java compilable code.

我在数据库字段中保存了一个比较表达式。我想从数据库中检索它,然后在条件结构中对它进行评估。

I have a comparative expression saved in a database field. I want to retrieve it from database, then evaluate it inside a conditional structure.

有没有办法做到这一点?

Is there any way to do this?

推荐答案

如果您使用的是Java 6,则可以尝试使用Java Compiler API。其核心是 JavaCompiler 类。您应该能够在内存中构建 Comparator 对象的源代码。

If you are using Java 6, you could try the Java Compiler API. At its core is the JavaCompiler class. You should be able to construct the source code for your Comparator object in memory.

警告:我实际上没有尝试过以下代码,因为JavaCompiler对象在我的平台上不可用,原因有些奇怪......

Warning: I have not actually tried the code below as the JavaCompiler object is not available on my platform, for some odd reason...

警告:编译任意Java代码可能对您的健康造成危害。

Warning: Compiling arbitrary Java code can be hazardous to your health.

考虑自己被警告......

Consider yourself warned...

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

After this, you just have to store the appropriate Java expression in your database field, referencing a and b.

这篇关于将字符串转换为代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆