groovy和java结合的常用两种使用方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/luoshi0801/article/details/84523153

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();
	}
	
}

 测试结果为:

 其中文本文件GroovyScript为

import org.apache.commons.lang.StringUtils;

List<String> parse(String log) {
    List<String> ret = new ArrayList<String>();
    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);
		}
	}

 

展开阅读全文

没有更多推荐了,返回首页