gpt4 book ai didi

grails - 嵌套闭包无法访问私有(private)静态字段

转载 作者:行者123 更新时间:2023-12-02 14:56:03 25 4
gpt4 key购买 nike

假设我有以下类(class):

@Slf4j
class MySuperclass {

public void testMethod() {
def test = [1, 2, 3]
test.each {it ->
log.info("gab" + it)
def test2 = [4,5,6]
test2.each {
log.info("" + it)
}
}
}
}

进而:
class MySubclass extends MySuperclass {

public void process() {
testMethod()
}
}

当我调用 mySubclass.process() ,我得到一个错误:
No such property log for class: com.ingenuity.app.kang.batch.MySubclass

该错误仅针对 test2 闭包内的行引发。如果我声明一个公共(public)日志字段,它工作正常。如果我添加 @Slf4j,它也可以正常工作子类中的注释。

我不明白这里发生了什么。这是一个时髦的错误吗?
我发现这个问题可能是相关的,但它不是相同的行为:
Groovy closure not work with static final field from super class

最佳答案

处理它的一种方法是将日志属性引用为类的静态成员。该项目位于https://github.com/jeffbrown/logissue证明了这一点。

https://github.com/jeffbrown/logissue/blob/d089c296c102980855a88061275e52485965e4ab/src/main/groovy/logdemo/MySuperclass.groovy

package logdemo

import groovy.util.logging.Slf4j

@Slf4j
class MySuperclass {

void testMethod() {
def test = [1, 2, 3]
test.each {it ->
log.info("gab" + it)
def test2 = [4,5,6]
test2.each {
MySuperclass.log.info("" + it)
}
}
}
}

这样可行。
~ $ git clone git@github.com:jeffbrown/logissue.git
Cloning into 'logissue'...
remote: Enumerating objects: 22, done.
remote: Counting objects: 100% (22/22), done.
remote: Compressing objects: 100% (15/15), done.
remote: Total 22 (delta 0), reused 22 (delta 0), pack-reused 0
Receiving objects: 100% (22/22), 53.62 KiB | 1.28 MiB/s, done.
~ $ cd logissue/
$ ./gradlew run

> Task :run
16:41:19.022 [main] INFO logdemo.MySuperclass - gab1
16:41:19.027 [main] INFO logdemo.MySuperclass - 4
16:41:19.027 [main] INFO logdemo.MySuperclass - 5
16:41:19.027 [main] INFO logdemo.MySuperclass - 6
16:41:19.027 [main] INFO logdemo.MySuperclass - gab2
16:41:19.027 [main] INFO logdemo.MySuperclass - 4
16:41:19.027 [main] INFO logdemo.MySuperclass - 5
16:41:19.027 [main] INFO logdemo.MySuperclass - 6
16:41:19.027 [main] INFO logdemo.MySuperclass - gab3
16:41:19.027 [main] INFO logdemo.MySuperclass - 4
16:41:19.027 [main] INFO logdemo.MySuperclass - 5
16:41:19.027 [main] INFO logdemo.MySuperclass - 6

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed

关于grails - 嵌套闭包无法访问私有(private)静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57146104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com