首页 > 学院 > 开发设计 > 正文

Groovy中Mixin注入

2019-11-08 01:55:08
字体:
来源:转载
供稿:网友

Groovy中Mixin注入

Mixin在可以在运行时将其他类的实现导入进来。1、通过Mixin注解。
class Helper {	def work() {		PRintln "$name is working"	}}@Mixin(Helper)class AGroovyClass {	def getName() { "AGroovyClass" }}new AGroovyClass().work() // AGroovyClass is working2、调用类的Mixin方法。
class Helper {	def work() {		println "$name is working"	}}class AGroovyClass {	def getName() { "AGroovyClass" }}AGroovyClass.mixin Helpernew AGroovyClass().work() // AGroovyClass is working3、在类的metaClass中调用mixin方法。
class Helper {	def work() {		println "$name is working"	}}class AGroovyClass {	def getName() { "AGroovyClass" }}AGroovyClass.metaClass.mixin Helpernew AGroovyClass().work() // AGroovyClass is working4、多个类mixin。
class Helper {    def work() {        println "$name is working"    }}class Num {    def add(val1, val2) {        println val1 + val2    }}class AGroovyClass {    def getName() { "AGroovyClass" }}AGroovyClass.mixin HelperAGroovyClass.mixin Num// AGroovyClass.metaClass.mixin Helper// AGroovyClass.metaClass.mixin Numnew AGroovyClass().work() // AGroovyClass is workingnew AGroovyClass().add(11, 12) // 23
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表