Home>Article>Java> Teach you how to dynamically call Groove code in Java

Teach you how to dynamically call Groove code in Java

坏嘻嘻
坏嘻嘻 Original
2018-09-14 11:50:03 3045browse

Grails is an open source framework for rapid web application development. It is based on the Groovy programming language and built on Spring, Hibernate and other standard Java frameworks, thereby bringing you a set of tools that can achieve ultra-high productivity. Standing frame.

1 Purpose

Dynamic execution of tasks or extended functions requires java to dynamically execute groovy code

2 Project dependencies

  org.codehaus.groovy groovy-all 2.5.2 pom   com.alibaba fastjson 1.2.49  

3 There are 3 dynamic executions of groovy code One way

GroovyShell: GroovyShell allows you to evaluate any Groovy expression in a Java class (even a Groovy class). You can use the Binding object to input parameters to the expression, and finally return the result of the Groovy expression through GroovyShell.

GroovyClassLoader: Use Groovy's GroovyClassLoader to dynamically load a script and execute its behavior. GroovyClassLoader is a customized class loader that is responsible for interpreting Groovy classes used in loading Java classes.

GroovyScriptEngine: GroovyShell is mostly used to deduce opposing scripts or expressions. If you switch to multiple interrelated scripts, it will be better to use GroovyScriptEngine. The GroovyScriptEngine loads Groovy scripts from the location you specify (file system, URL, database, etc.) and reloads them as the scripts change. Like GroovyShell, GroovyScriptEngine also allows you to pass in parameter values and can return script values.

4 Project structure

Teach you how to dynamically call Groove code in Java

##5 GroovyClassLoader method

Test groovy class

package com.chy import com.alibaba.fastjson.JSON import com.alibaba.fastjson.TypeReference /** * groove class */ class TestGroovy { void print() { System.out.println("hello word!!!!"); } List printArgs(String str1, String str2, String str3) { String jsonString = "[\""+str1+"\",\""+str2+"\",\""+str3+"\"]"; return JSON.parseObject(jsonString, new TypeReference>() {}); } }

Test java code

package com.chy; import groovy.lang.GroovyClassLoader; import groovy.lang.GroovyObject; import org.codehaus.groovy.control.CompilerConfiguration; import java.io.File; import java.util.List; /** * @Title: GroovyClassLoaderApp * @Description: 演示 GroovyClassLoader 方式 * @author chy * @date 2018/9/12 22:54 */ public class GroovyClassLoaderApp { private static GroovyClassLoader groovyClassLoader = null; public static void initGroovyClassLoader() { CompilerConfiguration config = new CompilerConfiguration(); config.setSourceEncoding("UTF-8"); // 设置该GroovyClassLoader的父ClassLoader为当前线程的加载器(默认) groovyClassLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), config); } public static void main(String[] args) { loadClass(); System.out.println("======================"); loadFile(); } /** * 通过类加载groovy */ private static void loadClass(){ GroovyObject groovyObject = null; try { groovyObject = (GroovyObject) GroovyClassLoaderApp.class.getClassLoader().loadClass("com.chy.TestGroovy").newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } // 执行无参函数 groovyObject.invokeMethod("print",null); System.out.println("============================"); // 执行有参函数 Object[] objects = new Object[]{"abc", "def", "ghi"}; List ls=(List) groovyObject.invokeMethod("printArgs", objects); ls.stream().forEach(System.out::println); } /** * 通过文件路径加载groovy * @return */ private static boolean loadFile(){ File groovyFile = new File("src/main/java/com/chy/TestGroovy.groovy"); if (!groovyFile.exists()) { System.out.println("文件不存在"); return false; } initGroovyClassLoader(); try { List result; // 获得TestGroovy加载后的class Class groovyClass = groovyClassLoader.parseClass(groovyFile); // 获得TestGroovy的实例 GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); // 反射调用printArgs方法得到返回值 Object methodResult = groovyObject.invokeMethod("printArgs", new Object[] {"chy", "zjj", "xxx"}); if (methodResult != null) { result =(List) methodResult; result.stream().forEach(System.out::println); } return true; } catch (Exception e) { System.out.println(e.getMessage()); } return false; } }

Related recommendations:

Groovy framework Grails 1.2 released

Based on AngularJS HTML Groovy to implement login function_AngularJS

The above is the detailed content of Teach you how to dynamically call Groove code in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn