groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srko─Ź <dinko.sr...@gmail.com>
Subject Re: No Such Property - When executing script from Java.
Date Thu, 18 Jun 2015 08:35:39 GMT
On 17 June 2015 at 18:08, Erick Nelson <ericksn@gmail.com> wrote:

> Yes, removing the &execute and changing invoke back to...
>
> void invoke (String action) {
>     this."${action}".execute()
> }
>
> does work , from Groovy, but when called from Java ....
>
>         File file = new File("src", "TestGroovy.groovy");
>         Class groovyClass = new GroovyClassLoader().parseClass(file);
>         GroovyObject groovyObject = (GroovyObject)
> groovyClass.newInstance();
>         groovyObject.invokeMethod("invoke", new String [] { "mailSent" });
>
> I get an error ...
>
> Exception in thread "main" java.lang.NullPointerException: Cannot invoke
> method execute() on null object. This is thrown from the
> this."${action}".execute() line.
>
> It is only when I use the &execute that it works in both Java and Groovy.
>

Hmmm. It works on my machine (my favourite line ;-) ):

-----------------------------------------
$ java -version
java version "1.7.0_76"
Java(TM) SE Runtime Environment (build 1.7.0_76-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.76-b04, mixed mode)
$ cat Bugger.groovy
import groovy.transform.Field

class Action {
    String actionName
    Action(actionName) {
        this.actionName = actionName
    }
    void execute() {
        println "Doing $actionName"
    }
}

@Field formFilled = new Action("Form Filled")

@Field mailSent = new Action("Mail Sent")

def invoke(action) {
    this."$action".execute()
}
$ cat Main.java
import java.io.File;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;

public class Main {

    public static void main (String [] args) {
        try {
            File file = new File("Bugger.groovy");
            Class grClass = new GroovyClassLoader().parseClass(file);
            GroovyObject groovyInstance = (GroovyObject)
grClass.newInstance();
            groovyInstance.invokeMethod("invoke", new String[] {
"mailSent"});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
$ javac -cp $GROOVY_HOME/embeddable/groovy-all-2.4.3.jar Main.java
$ java -cp $GROOVY_HOME/embeddable/groovy-all-2.4.3.jar:. Main
Doing Mail Sent
$
-----------------------------------------

Cheers,
Dinko

Mime
View raw message