Teach you how to dynamically call Groove code in Java
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>>() {}); } }
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; } }
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is
