groovy invokeMethod 添加方法到元类需要if 语句?
groovy invokeMethod add method to metaclass needs if statement?
我注意到 Groovy MetaClass 有一些奇怪的行为,我想知道是否有人可以给我一些线索来了解这里发生的事情。
这很好用:
@Override
Object invokeMethod(String name, Object args) {
if(true) {
println("Should only see this once")
def impl = { Object theArgs -> println("Firing WeirdAction") }
getMetaClass()."$name" = impl
return impl(args)
}
}
但是,如果我取消 if 语句,它会抛出 MissingPropertyException:
@Override
Object invokeMethod(String name, Object args) {
println("Should only see this once")
def impl = { Object theArgs -> println("Firing WeirdAction") }
getMetaClass()."$name" = impl
return impl(args)
}
这是我的 class 实例化和调用,class 除了上面的方法定义之外是空的。
IfTester sut = new IfTester()
sut.WeirdAction()
有人知道我在这里误解了什么吗?
使用 Groovy 2.4.5,问题似乎与 getMetaClass()
和 IfTester.getMetaClass()
有关。考虑:
class IfTester {
@Override
Object invokeMethod(String name, Object args) {
if (true) {
println "Should only see this once"
def impl = { def theArgs -> println "Firing WeirdAction" }
def mc1 = getMetaClass()
println "mc1: " + mc1
println "----"
def mc2 = IfTester.getMetaClass()
println "mc2: " + mc2
IfTester.getMetaClass()."$name" = impl
return impl(args)
}
}
}
IfTester sut = new IfTester()
sut.WeirdAction()
和if(true)
,那么mc1
和mc2
是一样的,都可以工作。没有 if
,mc1
是不同的,使用该样式会导致错误。
我不知道根本原因,也不知道它是否是错误。不知何故,似乎存在范围界定问题,或者 this
的含义在该上下文中有所不同。
我注意到 Groovy MetaClass 有一些奇怪的行为,我想知道是否有人可以给我一些线索来了解这里发生的事情。
这很好用:
@Override
Object invokeMethod(String name, Object args) {
if(true) {
println("Should only see this once")
def impl = { Object theArgs -> println("Firing WeirdAction") }
getMetaClass()."$name" = impl
return impl(args)
}
}
但是,如果我取消 if 语句,它会抛出 MissingPropertyException:
@Override
Object invokeMethod(String name, Object args) {
println("Should only see this once")
def impl = { Object theArgs -> println("Firing WeirdAction") }
getMetaClass()."$name" = impl
return impl(args)
}
这是我的 class 实例化和调用,class 除了上面的方法定义之外是空的。
IfTester sut = new IfTester()
sut.WeirdAction()
有人知道我在这里误解了什么吗?
使用 Groovy 2.4.5,问题似乎与 getMetaClass()
和 IfTester.getMetaClass()
有关。考虑:
class IfTester {
@Override
Object invokeMethod(String name, Object args) {
if (true) {
println "Should only see this once"
def impl = { def theArgs -> println "Firing WeirdAction" }
def mc1 = getMetaClass()
println "mc1: " + mc1
println "----"
def mc2 = IfTester.getMetaClass()
println "mc2: " + mc2
IfTester.getMetaClass()."$name" = impl
return impl(args)
}
}
}
IfTester sut = new IfTester()
sut.WeirdAction()
和if(true)
,那么mc1
和mc2
是一样的,都可以工作。没有 if
,mc1
是不同的,使用该样式会导致错误。
我不知道根本原因,也不知道它是否是错误。不知何故,似乎存在范围界定问题,或者 this
的含义在该上下文中有所不同。