简体   繁体   English

在Groovy中,println不使用重写的toString方法

[英]println does not use overriden toString method in Groovy

I have overriden toString() for my object: 我已经为我的对象重写了toString()

class GroovyTest {
    static class TestObject {
        int a = 3
    }
    static main(def s) {
        TestObject.metaClass.toString = { -> 'silly'}   
        println new TestObject()
    }
}

Ignoring my custom toString() it uses the default toString() and prints: 忽略我的自定义toString()它将使用默认的toString()并打印:

GroovyTest$TestObject@195ed659

However if I manually invoke it like println new TestObject().toString() it works: 但是,如果我像println new TestObject().toString()这样手动调用它,它将起作用:

Silly

Why is this? 为什么是这样?

When you override a method in Groovy you are not actually modifying the Java byte code for the class. 当您在Groovy中重写方法时,您实际上并没有在修改该类的Java字节码。 Your method gets added to a metaClass registry. 您的方法将添加到metaClass注册表中。 The method calls on the object are intercepted and the metaClass is checked. 对象上的方法调用将被拦截并检查metaClass

When a Groovy object is passed to Java code it will lose all of its Grooviness and become a POJO because method interception and metaClass checking will not happen there. 当Groovy对象传递给Java代码时,它将失去所有的Grooviness并成为POJO因为在那里不会发生方法拦截和metaClass检查。 See this post . 看到这篇文章

println internally uses System.out.println which bypasses the Groovy method interception and invokes Object.toString() . println内部使用System.out.println ,它绕过Groovy方法拦截并调用Object.toString()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM