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

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

问题描述

我想知道是否有任何方法可以将 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 表达式,引用 ab.

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

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

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