23 在java中使用groovy類

1       在java中使用groovy類

1.1  直接調用groovy類

在java中調用Groovy類,須要增長Groovy運行時到java的classpath中。java

pom.xmlui

<dependency>spa

           <groupId>org.codehaus.groovy</groupId>code

           <artifactId>groovy-all</artifactId>orm

           <version>2.4.5</version>xml

       </dependency>ip

 

建立一個包:de.vogella.groovy.javaci

建立一個Groovy類。get

package de.vogella.groovy.javaio

 

import groovy.transform.ToString

 

@ToString()

class Person {

    String firstName

    String lastName

    int age

    def address

}

 

建立一個java類

package de.vogella.groovy.java;

 

public class Main {

    public static void main(String[] args) {

       Person p = new Person();

       p.setFirstName("zuoys");

       p.setLastName("遙遠2");

       System.out.println(p.getFirstName() + " " + p.getLastName());

       System.out.println(p.toString());

    }

 

}

輸出:

zuoys 遙遠2

de.vogella.groovy.java.Person(zuoys, 遙遠2, 0, null)

 

1.2  Java調用Groovy腳本

http://www.tuicool.com/articles/baQRVf

 

JSR223方式

package de.vogella.groovy.java;

 

import java.util.Date;

 

import javax.script.Bindings;

import javax.script.Invocable;

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

 

public class ExecuteGroovyViaJSR223 {

 

    public static void main(String[] args) {

       ScriptEngineManager factory = new ScriptEngineManager();

       // 每次生成一個engine實例

       ScriptEngine engine = factory.getEngineByName("groovy");

       System.out.println(engine.toString());

       assert engine != null;

       // javax.script.Bindings

       Bindings binding = engine.createBindings();

       binding.put("date", new Date());

       // 若是script文原本自文件,請首先獲取文件內容

       try {

           engine.eval("def getTime(){return date.getTime();}", binding);

           engine.eval("def sayHello(name,age){return 'Hello,I am ' + name + ',age' + age;}");

           Long time = (Long) ((Invocable) engine).invokeFunction("getTime", null);

           System.out.println("執行結果:"+time);

           String message = (String) ((Invocable) engine).invokeFunction("sayHello", "zhangsan", new Integer(12));

           System.out.println("執行結果:"+message);

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }

 

    }

 

}

 

輸出

org.codehaus.groovy.jsr223.GroovyScriptEngineImpl@38af3868

執行結果:1469518145323

執行結果:Hello,I am zhangsan,age12

相關文章
相關標籤/搜索