java执行groovy的方式

 

脚本全文(不需要包名匹配,因为这是脚本):

println("hello!this is a script!");

类全文:

package co.java;

import java.io.File;
import java.io.IOException;

import org.codehaus.groovy.control.CompilationFailedException;

import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import groovy.util.GroovyScriptEngine;

public class InvokeGroovyTest
{
    public static void main(String[] args)
    {
        InvokeGroovyTest test = new InvokeGroovyTest();
       
//        test.way1();
        test.way2();
    }
   
    public void way1()
    {
        try
        {
            ClassLoader cl = InvokeGroovyTest.class.getClassLoader();
            GroovyClassLoader groovyCl = new GroovyClassLoader(cl);
            Class groovyClass = groovyCl.parseClass(new File("src/co/java/Script.groovy"));
            Script sc = (Script)groovyClass.newInstance();
            sc.run();
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
       
    }
   
    public void way2()
    {
        try
        {
            GroovyScriptEngine engine = new GroovyScriptEngine(".");
            engine.run("src/co/java/Script.groovy", (String)null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }       
    }
}


Total views.

© 2013 - 2018. All rights reserved.

Powered by Hydejack v6.6.1