简体   繁体   中英

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. 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.

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.

Since what you want is to parse and run this groovy file at runtime, you shouldn't care about this error. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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