Home Java javaTutorial Teach you how to dynamically call Groove code in Java

Teach you how to dynamically call Groove code in Java

Sep 14, 2018 am 11:50 AM

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>
Copy after login

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<String> printArgs(String str1, String str2, String str3) {
        String jsonString = "[\""+str1+"\",\""+str2+"\",\""+str3+"\"]";
        return JSON.parseObject(jsonString, new TypeReference<List<String>>() {});
    }

}
Copy after login

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;
    }
}
Copy after login
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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

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

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

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

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

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

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

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

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

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

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

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

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

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

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

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

See all articles