使用getter方法进行Groovy元编程

时间:2016-11-05 17:02:33

标签: groovy metaprogramming

有人会帮我弄清楚为什么这个添加的“get”方法适用于一个类(String)但不适用于另一个类(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 []

如何调用“foo”与类Node的getFoo()相同?

1 个答案:

答案 0 :(得分:1)

public class stations { public string station_code { get; set; } public string atcocode {get; set; } } public class Data { public DateTime request_time {get; set; } public IEnumerable<stations> Stations {get; set; } } var result = JsonConvert.DeserializeObject<Data>(json); foreach(stations s in result.Stations) { Console.WriteLine(s.station_code); } 将尝试在已解析的节点树中查找元素。直接使用nodes.foo将是AFAIK的唯一选择。