It's been almost a year since I've been in touch with groovy, and I've been trying to refer to groovy as a daily routine. Recently when doing a function, it took some time to re-see how Java calls Groovy's methods, pass parameters, and get the return value.
The example groovy code is as follows:
# Testgroovy.groovy defines the TESTC method, passing in 3 parameters, returning the processed data
def TESTC (intint int numc) {
" Incoming parameters: " " The sum of the calculations is: " + (NumA + NumB + NUMC)
# Groovy Returns the value of the last row by default
}
The sample Java code is as follows:
Importjava.io.File;ImportGroovy.lang.Groovyclassloader;ImportGroovy.lang.Groovyobject;public class Javausegroovytest {static Object Runwithgroovyclassloader () throws Exception {
//gets the current resource path used to specify the groovy script String Base_path= JavaUseGroovyTest.class.getResource ("/"). ToString ().Split("file:/")[1]; //Create Groovyclassloader using the context of the current thread//The Parseclass () method parses the file into a class class aclass that can be run= new Groovyclassloader (). Parseclass (New File (Base_path +"Testgroovy.groovy")); //creates a new instance of the class represented by this class object Groovyobject Groovyobject= (groovyobject) aclass.newinstance (); //the entry of the groovy method, multiple arguments are written from left to right, no import parameters remain empty new object[]{} object[] Objects= new object[]{1,3,2}; //Call method TESTC and get the return value (if the latter exists)returnGroovyobject.invokemethod ("TESTC",objects); } public static void Main (string[] args) throws Exception {
To print the return value to the consoleSystem. Out.println (Runwithgroovyclassloader ()); }}
Output Result:
Incoming parameters: 132 The sum of the calculations is:6
Work Essays--java Call the Groovy class's methods, pass parameters, and get return values