---
title: "java 调用groovy 脚本"
author: "flypeace"
date: "2011-07-01T16:59:20Z"
tags: []
categories: ["编程语言"]
slug: "java-groovy"
draft: false
lastmod: "2011-07-01T16:59:20Z"
id: 1112686
url: "https://host.iteye.com/blog/1112686"
---

1、groovy介绍  
         groovy 作为 java 语言的扩展，支持绝大多数java语法，运行在虚拟机上，可以直接使用java 的公共类库，很多代码都是用java实现的，少部分用groovy实现，所有能和groovy能和java无缝集成,groovy 被编译成java 字节码，能够在java和web中调用；  
    groovy是一个动态语言，也可以简单认为是脚本语言，具有动态语言的特性，像Python，ruby,SmallTalk等，非常灵活强大，能轻而易举实现 java中实现的功能。  
2、IDE支持  
    eclipse 和 netbeans 均支持groovy，有语法提示，高亮度显示，和java 一样，很方便。

3、java调用groovy脚本演示  
    以下代码演示了，如何在java中调用 groovy脚本，如果不需要用groovy IDE支持，在java 工程中需要引入groovy-all-1.7.10.jar 包，我用的是1.7.1，所以是1.7.10.jar，其他版本也行。

script.txt 文件中groovy脚本如下：  
def mul(x, y)  
{  
   new int\[1000];return x * y ;  
}  
 println mul(5, 7);  
 println(peace.aaa);

TestFileScript.java 测试类如下

import groovy.lang.GroovyShell;  
import groovy.lang.Script;

import java.io.File;

public class TestFileScript {  
private String aaa = "peace hello world!";

public String getAaa() {  
return aaa;  
}

public void setAaa(String aaa) {  
this.aaa = aaa;  
}

public void test() throws Exception {  
GroovyShell shell = new GroovyShell();  
File f = new File("script.txt");  
Script script = null;  
script = shell.parse(f);  
while (true) {  
script.setProperty("peace", this);  
Object result = script.run();  
}  
}

public static void main(String\[] args) throws Exception {

new TestFileScript().test();  
}  
}

运行该类，就可以看到结果；该测试案例，演示了，java语言执行脚本文件 script.txt ，并设置peace 属性，脚本中将TestFileScript 中的 aaa属性打印出来