groovy实战例子
所属分类 groovy
浏览量 1534
groovy 2.5.6
GroovyClassLoader
GroovyObject
// args = null or args = new Object[]{}
Object invokeMethod(String name, Object args);
void setProperty(String propertyName, Object newValue);
// 返回值类型 java.math.BigDecimal
String script = "c = (a + b*1.5) /3 ; return c";
// 返回值类型 java.lang.Double
// script = "double c = (a + b*1.5) /3 ; return c";
// 不写return 语句 空指针
script = "import java.util.*;Map map = new HashMap();map.put('a',1);return map;";
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
public class GroovyTest {
public static void main(String[] args) throws Exception {
// java.math.BigDecimal
String script = "c = (a + b*1.5) /3 ; return c";
// java.lang.Double
// script = "double c = (a + b*1.5) /3 ; return c";
GroovyClassLoader loader = new GroovyClassLoader();
Class groovyClass = loader.parseClass(script);
System.out.println("groovyClass="+groovyClass);
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
System.out.println("groovyObject="+groovyObject);
final Object[] params = new Object[]{};
groovyObject.setProperty("a", 1);
groovyObject.setProperty("b", 2);
Object result = groovyObject.invokeMethod("run", params);
System.out.println(result.getClass());
System.out.println(result);
result = groovyObject.invokeMethod("run", null);
System.out.println(result.getClass());
System.out.println(result);
// 不写 return , 空指针
script = "import java.util.*;Map map = new HashMap();map.put('a',1);return map;";
groovyClass = loader.parseClass(script);
System.out.println("groovyClass="+groovyClass);
groovyObject = (GroovyObject) groovyClass.newInstance();
System.out.println("groovyObject="+groovyObject);
result = groovyObject.invokeMethod("run", null);
System.out.println(result.getClass());
System.out.println(result);
}
}
输出结果
groovyClass=class script1563756252906453941321
groovyObject=script1563756252906453941321@77e9807f
class java.math.BigDecimal
1.3333333333
class java.math.BigDecimal
1.3333333333
groovyClass=class script15637562536951922541465
groovyObject=script15637562536951922541465@22635ba0
class java.util.HashMap
{a=1}
上一篇
下一篇
联合创始人和合伙人区别
性能压测谨慎使用监控工具
越是平凡的陪伴就越长久
prometheus使用技巧
linux ss 命令
上市首日 创业板 VS 科创板