2023-07-13

Grails how to change a metaclass Method

I'm trying to remove the square brackets that appear in toString off all collections in Grails. These square brackets are added in the toString of the java.util.AbstractCollection class. So the goal is to replace this toString method and I'm trying to use the ExpandoMetaClass.

I tried to use this code in the Bootstrap file:

 def init = { servletContext ->
     ExpandoMetaClass.enableGlobally()
     AbstractCollection.metaClass.toString << {-> "Test result" }
}

But the error occurs:

Caused by: groovy.lang.GroovyRuntimeException: Cannot add new method [toString] for arguments [[]]. It already exists!

I also tried with the = operator instead of <<. The error does not occur but it has no effect.

Does anybody know how to solve this?



No comments:

Post a Comment