Java 将字符串转换为代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/935175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:16:49  来源:igfitidea点击:

Convert String to Code

java

提问by

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

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

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?

有没有办法做到这一点?

回答by alamar

You can't because java is a compiled language.

你不能,因为 java 是一种编译语言。

You, however, should use a javax.scriptapi to execute code in runtime. JVM6 ships with Rhino (javascript interpreter) avaliable via javax.script.

但是,您应该使用javax.scriptapi 在运行时执行代码。JVM6 附带 Rhino(javascript 解释器),可通过javax.script.

http://java.sun.com/javase/6/docs/api/javax/script/package-summary.html

http://java.sun.com/javase/6/docs/api/javax/script/package-summary.html

There are javax.script-compatible java interpreters (and bean shell) avaliable.

javax.script兼容的 java 解释器(和 bean shell)可用。

https://scripting.dev.java.net/

https://scripting.dev.java.net/

回答by Kris

You can by using something like BeanShell.

您可以使用BeanShell 之类的东西。

回答by Jared

It's not fair to say that this is impossible. It is a very similar problem to the problem Java Server Pages (JSPs) have - in their case, there is code embedded in HTML files that needs to be compiled into a servlet and executed. If you really wanted to use that mechanism, I'm relatively sure you could dig through the source for a servlet containerand figure out how they did it (probably even reusing their mechanism to some degree.)

说这是不可能的,这是不公平的。这是一个与 Java Server Pages (JSP) 的问题非常相似的问题 - 在它们的情况下,HTML 文件中嵌入了需要编译到 servlet 并执行的代码。如果你真的想使用这种机制,我相对肯定你可以挖掘servlet 容器源代码并弄清楚他们是如何做到的(甚至可能在某种程度上重用他们的机制。)

However; it isn't an easy problem to solve (once you solve the obvious, immediate problem, you end up having to deal with issues with classloading and related problems.)

然而; 这不是一个容易解决的问题(一旦你解决了明显的、直接的问题,你最终不得不处理类加载和相关问题。)

It certainly would seem to be a better idea to go with the Java Scripting Platformin JDK6.

在 JDK6 中使用Java Scripting Platform似乎是一个更好的主意。

回答by Adam Paynter

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

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

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

警告:由于某些奇怪的原因,我还没有真正尝试过下面的代码,因为 JavaCompiler 对象在我的平台上不可用......

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

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

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();

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

在此之后,您只需将适当的 Java 表达式存储在您的数据库字段中,引用ab.

回答by Babar

Apparently Java Scripting Platformis better for this situation but You can also use Java Compiler Api. It provides methods for compiling java source files from within java code. In your case you can make a temporary file containing a class with your comparative expression then you can load that file and use it. Off course this isn't very elegant. Check out http://www.juixe.com/techknow/index.php/2006/12/13/java-se-6-compiler-api/for details on using Java Compiler Api

显然Java Scripting Platform更适合这种情况,但您也可以使用Java Compiler Api。它提供了从 Java 代码中编译 Java 源文件的方法。在您的情况下,您可以使用比较表达式创建一个包含类的临时文件,然后您可以加载该文件并使用它。当然,这不是很优雅。查看http://www.juixe.com/techknow/index.php/2006/12/13/java-se-6-compiler-api/有关使用 Java Compiler Api 的详细信息

回答by Thorbj?rn Ravn Andersen

A simple way to get code snippets to executable byte code is with the Javassist library.

将代码片段转换为可执行字节码的一种简单方法是使用 Javassist 库。

You can possibly adapt the techniques described in http://www.ibm.com/developerworks/java/library/j-dyn0610/to fit your needs.

您可以调整http://www.ibm.com/developerworks/java/library/j-dyn0610/ 中描述的技术以满足您的需要。

回答by Tim H

If you're getting the condition from a database, I'll wager there's a good chance that you might be wanting to use that condition to accessdata in that database.

如果您从数据库中获取条件,我敢打赌,您很有可能希望使用该条件来访问该数据库中的数据。

If you're using an ORM such as JPA or Hibernate (traditional or JPA), you might be able to formulate a dynamic query expression that you'd pass to the createQuery() method. This isn't as good as being able to do an on-the-fly compile of arbitrary Java code, but maybe it's all you need, and that particular solution doesn't require any special inclusions or actions, since the query language compiler is part of the ORM system itself.

如果您使用的是诸如 JPA 或 Hibernate(传统或 JPA)之类的 ORM,您或许能够制定一个传递给 createQuery() 方法的动态查询表达式。这不如能够对任意 Java 代码进行即时编译,但也许这就是您所需要的,并且该特定解决方案不需要任何特殊的包含或操作,因为查询语言编译器是ORM 系统本身的一部分。

Of course, if you DO do dynamic queries that way, I'd recommend logging them somehow, since it can be a real pain to figure out what went wrong after the fact if your query string is now in the garbage collector.

当然,如果您确实以这种方式进行动态查询,我建议您以某种方式记录它们,因为如果您的查询字符串现在在垃圾收集器中,那么在事后弄清楚出了什么问题可能会很痛苦。

回答by Huxi

Groovy might also be an option for you.

Groovy 也可能是您的选择。

It integrates cleanly with the Bean Scripting Framework, can be embedded directlyquite easily and might be ok, syntax-wise, for you.

它与Bean Scripting Framework完美集成,可以很容易地直接嵌入,并且在语法方面对您来说可能没问题。

回答by KarlP

You shouldn't. Really!

你不应该。真的!

Are you inventing another enterprise rules engine?. You might want to readthese links.

您正在发明另一个企业规则引擎吗?. 您可能想阅读这些链接。

Consider the fact that the only people that is skilled enough to write code and then insert it into a database, probably are having an editor and a compiler anyway...

考虑到只有足够熟练地编写代码然后将其插入数据库的人,可能无论如何都拥有编辑器和编译器......

The compiler will catch all those pesky syntax errors and you can even test the code! Remember that editors and compilers, and even computer languages were invented to help the programmer to comfortably write comprehensible code with a reasonable effort.

编译器将捕获所有那些讨厌的语法错误,您甚至可以测试代码!请记住,编辑器和编译器,甚至计算机语言的发明都是为了帮助程序员以合理的努力轻松地编写易于理解的代码。

While I'm at it: read about the complicators glovestoo!

当我在做的时候:也请阅读有关复杂手套的信息

回答by Cameron Pope

If all you really need to do is evaluate an expression stored in a database, you might want to look at JEP (Java Expression Parser)

如果您真正需要做的只是评估存储在数据库中的表达式,您可能需要查看 JEP(Java Expression Parser)

The latest (commercial) version is here.

最新(商业)版本在这里

A slightly older, GPL version is here

一个稍旧的 GPL 版本在这里

Some examples for usage.

一些用法示例