Groovy code execution in java at runtime

Is it possible to execute groovy code dynamically loaded into a java application. For example, there is a database table containing small pieces of groovy code, for example:

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 that will be inserted during java code execution, for example:

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

Is there any way to evaluate such a piece of groovy code? Or maybe you would advise me on a different approach on how to implement this.

+3
source share
4 answers

Yes you can do it.

See link http://groovy.codehaus.org/Embedding+Groovy

, , , . , - , , ... , .

+10

JavaScript Groovy. ? Rhino JavaScript JDK. , Groovy , .

+4

Java 6 Java Scripting API . API Java Java.

Java Scripting .

+2

Yes, you can use the Groovy script engine to evaluate Groovy source code at runtime - and, of course, the source code can be the result of replacing strings.

From what I remember, there are various ways you can achieve this, and it will have different pros and cons.

<plug> See Chapter 11 Groovy in action for more information . </ fork>

+1
source

Source: https://habr.com/ru/post/1751203/


All Articles