How to use interface to call Groovy method in Java
Editor to share with you how to use the interface to call the Groovy method in Java, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
1. Define the Java interface to include the 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 implements IFoo {
Public Object run (Object foo) {
Println 'Hello Worldwide'
X = 123
Foo * 10}}
3. Dynamically load the Groovy class, create an interface instance, and call the methods 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 ();}
}
}
These are all the contents of the article "how to use interfaces to call Groovy methods in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!