Work Essays--java Call the Groovy class's methods, pass parameters, and get return values

Source: Internet
Author: User
Tags groovy script

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.