TX T TX T - 1 year ago 177
Groovy Question

Groovy Meta Programming with getter method

Would someone help me figure out why this added "get" method works with one class(String) but not the other class(Node)?

String.metaClass.getFoo = { "string foo" }
s = "test"
println s.foo // WORKS: get "string foo"

Node.metaClass.getFoo = { "node foo" }
xml = "<test><body>test</body></test>"
nodes = new XmlParser().parseText(xml)
println nodes.foo // NOT WORK: gets []

How do I make calling the "foo" resulting the same as getFoo() for class Node?

Answer Source

nodes.foo will try to find an element in the parsed tree of nodes. Directly using getFoo() would be the only option AFAIK.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download