作者:cuishy | 来源:互联网 | 2023-05-18 20:50
文章目录一、报错信息二、解决方案一、报错信息使用MetaClass为类注入方法时,如果注入的方法与类中原有的方法有冲突,classStudent{defname;defhello
一、报错信息
使用 MetaClass 为类注入方法时 , 如果注入的方法与类中原有的方法有冲突 ,
class Student {def name;def hello() {println "Hello " + name}
}
Student.metaClass.hello << {println delegateprintln "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 元对象协议与元编程 ( 方法注入 | 使用 &#64;Category 注解进行方法注入 | 分类注入方法查找优先级 ) 博客 ;
使用 MetaClass 的方式注入方法 , 注入的方法不可与原来的方法冲突 , 否则就会报上述错误 ; 参考 【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 使用 MetaClass 进行方法注入普通方法 ) 博客 ;