groovy调用java Bean的方法

有时候,当脚本需要很多传参时,这是我们就需要把参数封装到一个model类里面,而且也容易辨认。反之亦然

java代码如下:

packagemain.testJava;

importgroovy.lang.Binding;

importgroovy.lang.GroovyObject;

importgroovy.util.GroovyScriptEngine;

importmain.TestVO;

import staticjava.lang.Thread.sleep;

/**

*@author:lb

*@Description:

*@Date:Createdin 10:39 2018/1/8

*@Modifiedby

*/

public classJavaUseGroovyTest {

public static voidmain(String[] args)throwsException {

//将返回值打印到控制台

// System.out.println(runWithGroovyClassLoader());

String[] roots =newString[] {"src/main/groovy"};

GroovyScriptEngine engine =newGroovyScriptEngine(roots);

Binding binding =newBinding();

binding.setVariable("numA",1);

binding.setVariable("numB",1);

binding.setVariable("numC",1);

//不指定方法名,直接调用整个脚本

Object value = engine.run("HelloGroovy.groovy",binding);

System.out.println(value);

while(true){

System.out.println(value);

sleep(500);

GroovyObject groovyObject = (GroovyObject) engine.loadScriptByName("HelloGroovy.groovy").newInstance();

Object[] params =newObject[]{1,2};

TestVO testVO =newTestVO();

testVO.setAge(18);

testVO.setName("me");

//调用指定脚本方法时

value = groovyObject.invokeMethod("testC",testVO);

System.out.println(value);

}

}

}

groovy 脚本代码如下:

packagemain.groovy

importmain.TestVO

/**

*@author:lb

*@Description:

*@Date:Createdin 15:13 2018/1/6

*@Modifiedby

*/

//TestGroovy.groovy定义testC方法,传入3个参数,返回处理后的数据

println("$numA,$numB,$numC")

deftestC(TestVO testVO) {

// "传入参数:" + a + "计算之和为:" + (a+b+6)

// groovy会默认返回最后一行的值

// if(a == 1){

// a = 2

// }

// return a

TestVO testVO1 =newTestVO()

testVO1.age=10

returntestVO1

}

你可能感兴趣的:(groovy调用java Bean的方法)