add extension module to groovy class

吃可爱长大的小学妹 提交于 2019-12-01 10:54:39

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!