Strange behavior of adding dynamic methods on Groovy NodeChild

I use Grails XML Parser to parse the XML string and after receiving the processed instance NodeChild, I add dynamic methods in this case, as shown below:

import grails.converters.XML
import groovy.util.slurpersupport.NodeChild

NodeChild result = XML.parse("<root></root>")

result.getMetaClass().methodA = { return "a" }
result.getMetaClass().methodB = { return "b" }

println rootNode.methodA()
println rootNode.methodB()

Now, when I call methodA()and expect that "a" will be printed, I get MissingMethodExceptionthat it is methodA()not found.

I researched this for some time and found that all dynamic methods are replaced by the last dynamic method that we add, i.e. in this case: methodB()replaces (or does something) methodA(), so I call and type first methodB(), it will print "b" correctly.

This leads me to another test as follows:

import grails.converters.XML
import groovy.util.slurpersupport.NodeChild

String result = "any-other-data-type-instance-here-to-inject-dynamic-methods"

result.getMetaClass().methodA = { return "a" }
result.getMetaClass().methodB = { return "b" }

println rootNode.methodA()
println rootNode.methodB()

. NodeChild. metanlass exando , . , ?

+4
1

, , , . , , - , , .

:

import grails.converters.XML
import groovy.util.slurpersupport.NodeChild

NodeChild.metaClass.methodA = { return "a" }
NodeChild.metaClass.methodB = { return "b" }

NodeChild result = XML.parse("<root></root>")

println result.methodA()
println result.methodB()

, it, , Groovy null. , :

NodeChild.metaClass.methodA = { -> return "a" }
NodeChild.metaClass.methodB = { -> return "b" }
+1

Source: https://habr.com/ru/post/1569605/


All Articles