我是靠谱客的博主 怕孤独煎蛋,这篇文章主要介绍Java项目中使用groovy的两种方式,现在分享给大家,希望可以做个参考。

可能还有更多的使用方式,在此只记录自己使用的两种方式:

方式一

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
String type = "List<String>"; String jsonString = "["wei.hu","mengna.shi","fastJson"]"; Binding binding = new Binding(); binding.setProperty("jsonString", jsonString); binding.setProperty("type", type); GroovyShell groovyShell = new GroovyShell(binding); return groovyShell.evaluate( "import com.alibaba.fastjson.JSON;n" + "import com.alibaba.fastjson.TypeReference;n" + "TypeReference<"+ type +"> typeReference = new TypeReference<" + type +">(){};n" + "JSON.parseObject(jsonString, typeReference);" );

方式二

1、定义一个groovy文件 test.groovy:
(这里有一个有意思的地方:无论将groovy文件放在java资源的哪一个目录下,IDEA都会将其对应的class文件放在resource目录的根目录下)

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; def test(String str1, String str2, String str3) { printf(str1 + " " + str2 + " " + str3) def clos = {println "Hello ${it}"}; clos.call(str1); String jsonString = "["wei.hu","mengna.shi","fastJson"]" return JSON.parseObject(jsonString, new TypeReference<List<String>>() {}) } test()

2、java调用

复制代码
1
2
3
4
GroovyObject groovyObject = (GroovyObject) ConfigInfoController.class.getClassLoader().loadClass("test").newInstance(); Object[] objects = new Object[]{"abc", "def", "ghi"}; groovyObject.invokeMethod("test", objects);

最后

以上就是怕孤独煎蛋最近收集整理的关于Java项目中使用groovy的两种方式的全部内容,更多相关Java项目中使用groovy内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(79)

评论列表共有 0 条评论

立即
投稿
返回
顶部