Groovy:元编程(方法注入)
2020-06-18 本文已影响0人
lv_mock
category分类注入
class Req {
static def get(String self) {
println "Req_get_" + self.length()
}
}
use(Req) {
"AAA".get()
}
//output:
Req_get_3
@Category(String)
class StringUtils {
def get() {
println "StringUtils_get_" + length()
}
}
use(StringUtils) {
"BBBB".get()
}
//output:
StringUtils_get_4
class Req {
static def get(String self) {
println "Req_get_" + self.length()
}
}
@Category(String)
class StringUtils {
def get() {
println "StringUtils_get_" + length()
}
}
use(Req,StringUtils) {
"CC".get()
}
use(StringUtils,Req) {
"CC".get()
}
//output
StringUtils_get_2
Req_get_2
使用metaclass实现方法注入
String.metaClass.get = {
delegate.toString().length()
}
println "AAA".get()
//output:
3
静态方法注入
String.metaClass.'static'.printlnClass = {
println delegate.toString() + "_" + delegate.toString().length()
}
"AAA".printlnClass()
String.printlnClass()
//output:
AAA_3
class java.lang.String_22
构造函数注入
String.metaClass.constructor = {
Calendar calendar ->
new String(calendar.getTime().toString())
}
println new String(Calendar.instance)
//output:
Thu Jun 18 17:12:26 GMT+08:00 2020
String.metaClass {
get = {
delegate.toString().length()
}
'static' {
printlnClass = {
delegate.toString() + "_" + delegate.toString().length()
}
}
constructor = {
Calendar calendar ->
new String(calendar.getTime().toString())
}
}
println "AAA".get()
println "AAA".printlnClass()
println new String(Calendar.instance)
//output
3
AAA_3
Thu Jun 18 17:16:25 GMT+08:00 2020
println String.metaClass
String.metaClass.get = {
}
println String.metaClass
//output
org.codehaus.groovy.runtime.HandleMetaClass@6d5620ce[groovy.lang.MetaClassImpl@6d5620ce[class java.lang.String]]
groovy.lang.ExpandoMetaClass@70e38ce1[class java.lang.String]
def emc = new ExpandoMetaClass(String)
emc.toUpperCase = {
delegate.toString() + "_emc"
}
emc.initialize()
String.metaClass = emc
println "abc".toUpperCase()
String.metaClass = null
println "abc".toUpperCase()
//output
abc_emc
ABC
混合注入
class Req2 {
def get(String url) {
url.length()
}
}
String.mixin(Req2)
println "aaa".get("bbbb")
//output
4
class Req2 {
def get(String url) {
url.length()
}
}
String.metaClass.mixin(Req2)
println "aaa".get("bbbb")
//output
4
@Mixin(String)
class Req2 {
def get(String url) {
url.length()
}
}
println new Req2().get("aaa")
//output
3
class A {
def get(String str) {
"a"
}
}
class B {
def get(String str) {
"b"
}
}
String.mixin(A,B)
println "".get("")
String.mixin(B,A)
println "".get("")
//output:
b
a