---
title: "groovy和java结合的常用两种使用方式"
author: "luoshi0801"
date: "2014-01-26T15:30:02Z"
tags: []
categories: ["行业应用"]
slug: "groovy-java"
draft: false
lastmod: "2014-01-26T15:51:52Z"
id: 2009570
url: "https://luoshi0801.iteye.com/blog/2009570"
---

groovy是基于JVM的一种敏捷动态语言，可以在不改动正在运行着程序的情况下为系统动态增加特性

 

方法一：通过类加载

 

```
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;

import org.codehaus.groovy.runtime.InvokerHelper;

import com.google.common.collect.Maps;

public class GroovyTest {
	
	static class MyBinding extends Binding {
		
		private HashMap<String, Object> variables = Maps.newHashMap();

		public void setVariable(String name, Object binding) {
			variables.put(name, binding);
		}
		
		public Object getVariable(String name) {
	        return variables.get(name);
	    }
	}
	
	public static void main(String[] args) {
		String log = "Hi, test one, split with comma";
		
		GroovyClassLoader classLoader = new GroovyClassLoader ();
		Class<?> scriptClass = classLoader.parseClass(getGroovyString());
		Script script = InvokerHelper.createScript(scriptClass, new MyBinding());
		List<String> ret = (List<String>)script.invokeMethod("parse", new Object[]{log});
		
		System.out.println(ret);
	}
	
	private static String getGroovyString() {
		StringBuilder ret = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(GroovyTest.class.getClassLoader()
				.getResourceAsStream("GroovyScript")));
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				ret.append(line).append("\n");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return ret.toString();
	}
	
}
```

 测试结果为：  
![](http://dl2.iteye.com/upload/attachment/0093/5534/0f53a6e1-a591-3e6e-b433-229bd453024c.jpg)

 其中文本文件GroovyScript为

import org.apache.commons.lang.StringUtils;

List&lt;String&gt; parse(String log) {  
    List&lt;String&gt; ret = new ArrayList&lt;String&gt;();  
    for (field in StringUtils.split(log, ",")) {  
        ret.add(field);  
    }  
    return ret;  
}

 

 

方法二：通过evaluate

```
        @Test
	public void test() {
		Binding binding = new Binding();
		binding.setVariable("$name", "zhiyuan");
		binding.setVariable("$age", 28);
		binding.setVariable("$salary", 1000);
		GroovyShell shell = new GroovyShell(binding);
		
		String groovyExp = "return ($name.contains('hiy')  && $age > 27) || $salary <= 1000";
		Boolean val = (Boolean)shell.evaluate(groovyExp);
		if (val) {
			System.out.println(groovyExp);
		}
	}
```