简体   繁体   English

在运行时在java中执行Groovy代码

[英]Execution of Groovy code in java at runtime

Is it possible to execute groovy code dynamically loaded in java application. 是否可以执行在java应用程序中动态加载的groovy代码。 For example there is a database table which contains small pieces of groovy code, like: 例如,有一个数据库表,其中包含一小段groovy代码,如:

def test(${val_to_insert_from_java}){
    if (${val_to_insert_from_java} > 10){
        return true;
    }
    return false;
}

Where ${val_to_insert_from_java} is a placeholder for some real value which gonna be inserted during execution of java code, like: 其中${val_to_insert_from_java}是一个占位符,用于在执行java代码期间插入的某些实际值,例如:

String groovyFuncSource = getFromDb();
groovyFuncSource.replace(${val_to_insert_from_java}, 9);
Object result = <evaluate somehow groovyFuncSource>;

Is there is a way to evaluate such piece of Groovy code? 有没有办法评估这样的Groovy代码? Or may be you advise me some other approach how to implemnt this. 或者你可能会告诉我一些其他方法如何实现这一点。

Yes, you can do this. 是的,你可以这样做。

See the link http://groovy.codehaus.org/Embedding+Groovy 请参阅http://groovy.codehaus.org/Embedding+Groovy链接

You may want to use caution with this approach, because executing code stored in a database will introduce security flaws in your application. 您可能需要谨慎使用此方法,因为执行存储在数据库中的代码会在应用程序中引入安全漏洞。 For example, some code maliciously inserted as text in your database could do ... almost anything unless you're checking it. 例如,一些恶意插入数据库中的文本代码几乎可以做任何事情,除非你检查它。

An alternative would be to use JavaScript instead of Groovy. 另一种方法是使用JavaScript而不是Groovy。 Why? 为什么? Because the Rhino JavaScript engine already comes with the JDK . 因为Rhino JavaScript引擎已经附带了JDK So if you aren't already using Groovy in your projects, it's one less dependency. 因此,如果您尚未在项目中使用Groovy,那么它的依赖性会降低一个。

From Java 6 you can use Java Scripting API to do that. 从Java 6开始,您可以使用Java Scripting API来完成此任务。 Java scripting API allows you to use various scripting languages within Java apps. Java脚本API允许您在Java应用程序中使用各种脚本语言。

You can find more about Java Scripting here . 您可以在此处找到有关Java Scripting的更多信息。

Yes, you can use the Groovy script engine to evaluate Groovy source code at execution time - and of course that source code can be the result of string replacements. 是的,您可以使用Groovy脚本引擎在执行时评估Groovy源代码 - 当然,源代码可以是字符串替换的结果。

From what I remember, there are various ways you can accomplish this, which will have different pros and cons. 从我记忆中,你可以通过各种方式实现这一目标,这将有不同的优点和缺点。

<plug> See chapter 11 of Groovy in Action for more details. <plug>有关更多详细信息,请参阅Groovy in Action的第11章。 </plug> </插头>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM