Details
-
Type:
Sub-task
-
Status:
Open
-
Priority:
Major
-
Resolution: Unresolved
-
Affects Version/s: 1.5.4
-
Fix Version/s: None
-
Component/s: None
-
Labels:None
-
Testcase included:yes
-
Number of attachments :
Description
If toString is overridden via the metaClass then "$
{obj}" != obj.toString().
Test case below
class DateTest extends GroovyTestCase { void testToString(){ Date.metaClass.toString = { -> 'boogie' } def date = new Date() assertEquals('boogie', date.toString()) assertEquals( date.toString(), "${date}") //fails } }
Paul King gave this pointer as to where the problem is:
"Yes, the final line of InvokerHelper.format() should be something like:
return (String) invokeMethod(arguments, "toString", EMPTY_ARGS);
//return arguments.toString();
to make your example work."
Issue Links
- is duplicated by
-
GROOVY-2732
GString doesn't call correct toString method when it's been changed via the metaClass mechanism
-
- relates to
-
GROOVY-2801
Override toString in coerced Map fails for interfaces but is ok for concrete classes
-
There are other cases that do not work. Some of them require additional code to be fixed.
Date.metaClass.toString = {-> "silly"} assert new Date().toString() == "silly" // similar assert "".plus(new Date()) != "silly" assert [new Date()].toString() != ["silly"].toString() // but also e.g. assert "".leftShift(new Date()).toString() != "silly" assert "silly".isCase(new Date()) == false def s = new StringBuffer("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") s[1..5] = new Date() assert s.indexOf("silly") == -1But since
what seems to be intent, it is probably a good idea to have a faster invocation for classes that don't allow overriding toString().