简体   繁体   English

在Java中执行Groovy文件

[英]Executing groovy file in Java

I am trying to execute a .groovy file in Java however being new to both Java and Groovy I am having some problems. 我试图在Java中执行.groovy文件,但是对于Java和Groovy来说都是新手,所以我遇到了一些问题。 I'm doing this to learn more and would appreciate if someone could tell me what i am doing wrong. 我正在这样做以了解更多信息,如果有人可以告诉我我在做什么错,我将不胜感激。

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;

import javax.naming.Binding;
import java.io.File;

public class testClass extends GroovyShell{

    public static void main(String[] args){

        try{
            ClassLoader parent = testClass.class.getClassLoader();
            GroovyClassLoader loader = new GroovyClassLoader(parent);
            Class groovyClass = loader.parseClass(new File("src/testg.groovy"));

            GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
            Object[] args1 = {};
            groovyObject.invokeMethod("run",args1);


        }catch(Exception e) {
        System.out.println("error loading file");
             }
    }

}

I am getting the following errors : 我收到以下错误:

Groovyc: Cannot compile Groovy files: no Groovy library is defined for module 'Prep'
Using javac 1.7.0_09 to compile java sources
Compilation completed with 1 error and 0 warnings in 9 sec
1 error
0 warnings
Groovyc: Internal groovyc error: code 1

Or perhaps someone could give me an example of how to execute eg hello world script written in groovy, in java. 也许有人可以给我一个例子,说明如何执行用Java groovy编写的hello world脚本。

That's not an error thrown by your code. 这不是您的代码引发的错误。 It's an error thrown by IntelliJ, which tries to compile your .groovy file to a .class file. 这是IntelliJ引发的错误,它试图将.groovy文件编译为.class文件。

Since what you want is to parse and run this groovy file at runtime, you shouldn't care about this error. 由于您想要的是在运行时解析并运行该groovy文件,因此您无需关心此错误。 Or rather, to avoid it, you should not put the .groovy file in a directory marked as a source directory in the IntelliJ project, so that IntelliJ doesn't try to compile it. 或者,为了避免这种情况,您不应将.groovy文件放在IntelliJ项目中标记为源目录的目录中,以便IntelliJ不会尝试对其进行编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM