使用 MetaClass 为类注入方法时 , 如果注入的方法与类中原有的方法有冲突 ,
class Student {
def name;
def hello() {
println "Hello " + name
}
}
// 向 Student 类注入 hello 方法
Student.metaClass.hello << {
println delegate
println "Hello ${delegate.name}"
}
执行上述方法 , 会有如下报错 ;
报错信息 :
Caught: groovy.lang.GroovyRuntimeException: Cannot add new method [hello] for arguments [[]]. It already exists!
groovy.lang.GroovyRuntimeException: Cannot add new method [hello] for arguments [[]]. It already exists!
at Groovy.run(Groovy.groovy:11)
如果使用 Category 分类的方式注入方法 , 注入的方法可以与类中原来的方法相同 , 参考 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 @Category 注解进行方法注入 | 分类注入方法查找优先级 ) 博客 ;
使用 MetaClass 的方式注入方法 , 注入的方法不可与原来的方法冲突 , 否则就会报上述错误 ; 参考 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入普通方法 ) 博客 ;