简体   繁体   中英

Execution of Groovy code in java at runtime

Is it possible to execute groovy code dynamically loaded in java application. For example there is a database table which contains small pieces of groovy code, like:

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:

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? 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

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. Why? Because the Rhino JavaScript engine already comes with the JDK . So if you aren't already using Groovy in your projects, it's one less dependency.

From Java 6 you can use Java Scripting API to do that. Java scripting API allows you to use various scripting languages within Java apps.

You can find more about Java Scripting here .

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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