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
<dependencies> <dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.5.2</version> <type>pom</type> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.49</version> </dependency> </dependencies>
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
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<String> printArgs(String str1, String str2, String str3) { String jsonString = "[\""+str1+"\",\""+str2+"\",\""+str3+"\"]"; return JSON.parseObject(jsonString, new TypeReference<List<String>>() {}); } }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<String> ls=(List<String>) 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<String> 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<String>) 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!

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

如何使用Vue.js和Groovy语言构建可扩展的数据处理系统引言:随着互联网和大数据的快速发展,数据处理系统变得越来越重要。Vue.js作为一种流行的前端框架,以其简洁的语法和易用性在开发中得到广泛应用。而Groovy语言则是一门在Java虚拟机上运行的强大的动态语言,能够与Java无缝集成。在本文中,我们将介绍如何使用Vue.js和Groovy语言构建一

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

利用MySQL和Groovy开发:如何实现数据批量操作功能在开发过程中,有时我们需要对数据库中的数据进行批量操作,比如插入大量数据、更新多个记录或删除多个记录等。为了提高效率,我们可以利用MySQL和Groovy开发,实现数据批量操作功能。本文将介绍如何使用Groovy和MySQL来实现这一功能,并提供相应的代码示例。一、准备工作在开始之前,我们需要确保已经

封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
