我正在使用一个带有 Spring Social 的小型 Groovy 应用程序来使用来自 Twitter 的流。我现在想记录我收到的每条推文,包括一些细节。
如果 Tweet
类在我自己的代码中,我可以轻松地这样做以获得良好的日志输出:
import groovy.transform.ToString
@ToString
class Tweet {
// fields...
}
但是由于我要记录的类在 Spring Social 中,所以我不能那样做。是否有覆盖 toString
方法的“Groovy”方法?
向 metaClass
添加 toString
闭包并没有真正帮助,因为我不想在每个日志输出时显式调用 toString
.
org.springframework.social.twitter.api.Tweet.metaClass.toString = {
"${delegate.field1}, ${delegate.field2}"
}
// still prints "received tweet [org.springframework.social.twitter.api.Tweet@637c1991]"
log.info("received tweet [{}]", tweet)
// prints "received tweet [field1 field]"
log.info("received tweet [{}]", tweet.toString())
最佳答案
是的,你可以做到。 Groovy 有能力使用元类功能将新方法注入(inject)现有类。当您在类上调用方法时,会检查所谓的元类注册表以查看该类实例是否存在元类扩展方法。
简单定义:
Tweet.metaClass.toString = {"${delegate.field}, ${delegate.anotherField}"}
关于groovy - 在 Groovy 中为您不拥有的类覆盖 toString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256159/