Another way to call the Groovy method in Java: Use the interface

xiaoxiao2021-03-06  59

1. Define the Java interface to include a Groovy method that needs to be called in Java

Public interface ifoo {

Public Object Run (Object foo);

}

2. Create a Groovy class to implement the interface

Class foo imports ifoo {

Public Object Run (Object foo) {

Println 'Hello World!'

X = 123

FOO * 10

}

}

3, dynamically load the Groovy class, create an interface instance, call the method defined in the interface

Import groovy.lang.groovyclassloader;

Import java.io.file;

Public class invokegroovy {

Public static void main (String [] args) {

ClassLoader Cl = New InvokeGroovy (). GetClass (). GetClassLoader ();

GroovyclassLoader Groovycl = New GroovyclassLoader (CL);

Try {

Class Groovyclass = Groovycl.Parseclass (New File ("src / foo.groovy));

Ifoo foo = (ifoo) groovyclass.newinstance ();

System.out.println (foo.run (new integer (2)));

} catch (exception e) {

E.PrintStackTrace ();

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-111757.html

New Post(0)