add extension module to groovy class

后端 未结 1 352
别跟我提以往
别跟我提以往 2021-01-15 10:41

I am trying to create simple extension module.

I created Main.groovy file

class Item {
   String item
}

new Item().sayHell         


        
相关标签:
1条回答
  • 2021-01-15 11:40

    Your extension method has to be static to be recognized (because extension modules have to be stateless) and the Item class has to live into its own source file to be recognized (because otherwise it's an inner class of the script).

    Here is a bash script that does what you want:

    #!/bin/bash
    
    echo "Create Item.groovy"
    cat > 'Item.groovy' <<-EOF
    class Item {
        String item
    }
    EOF
    
    echo "Compile Item.groovy"
    groovyc Item.groovy -d classes
    
    echo "Create extension module class"
    cat > 'ItemExtension.groovy' <<-EOF
    class ItemExtension {
        static def sayHello(Item self) {
            println "hello world"
        }
    }
    EOF
    
    echo "Create extension module descriptor"
    mkdir -p classes/META-INF/services
    cat > classes/META-INF/services/org.codehaus.groovy.runtime.ExtensionModule <<-EOF
    moduleName=Item extension module
    moduleVersion=1.0
    extensionClasses=ItemExtension
    EOF
    
    echo "Compile extension module"
    groovyc -cp classes ItemExtension.groovy -d classes
    
    echo "Creating script.groovy"
    cat > 'script.groovy' <<-EOF
    new Item().sayHello()
    EOF
    
    echo "Run script"
    groovy -cp classes script.groovy
    
    0 讨论(0)
提交回复
热议问题