1.respondsTo方法判断对象是否存在指定方法

interface IHelp{
    void helpMoveThings()
}

class Man implements IHelp{
    void helpMoveThings(){
        println 'Man help move things'
    }
}


class WoMan implements IHelp{
    void helpMoveThings(){
        println 'WoMan help move things'
    }
}

class Elephant implements IHelp{
    void helpMoveThings(){
        println 'Elephant help move things'
    }
    
    void eatSugarcane(){
        println 'Elephant eat sugarcane'    
    }
}

def takeHelp(helper){
    helper.helpMoveThings()
    if(helper.metaClass.respondsTo(helper, 'eatSugarcane')){
        helper.eatSugarcane()
    }
}

takeHelp(new Man())
takeHelp(new WoMan())
takeHelp(new Elephant())

/*output
Man help move things
WoMan help move things
Elephant help move things
Elephant eat sugarcane
*/

2.向类中注入方法

def shoutString(String str){
    println str.shout()
}

str = 'hello'
str.metaClass.shout = {->toUpperCase()}

shoutString(str)
/*output
HELLO
*/