I deal a lot with the pre-generics like Maps with Strings as the keys. They are mapping the keys to one of the following types of values:
- Another Map
- A List
- Primitives wrappers
You can access the collection content using either XPath or queries like that:
myMap/FIRST_LIST[2]/SECOND_LIST[1]/MY_MAP/MY_PRIMITIVE
What I am looking for is a library that would allow me to apply a visitor function to the multiple elements of a collection. The basic functionality could look like that
MyMapBrowser browser = new MyMapBrowser(myMap);
browser.applyVisitor("FIRST_LIST[*]/SECOND_LIST[*]/MY_MAP/MY_PRIMITIVE",
new AbstractVisitor<String>() {
visit(String s) {
// do something with the strings
}
});
It would be also wonderful to have a possibility to first register multiple visitors for various levels of collection and then start the visiting iteration. It could look like this:
browser.registerVisitor(SECOND_LIST, new AbstractVisitor<MyList> { ... )
browser.doVisiting("FIRST_LIST[*]/SECOND_LIST[*]/MY_MAP/MY_PRIMITIVE");
In fact I’ve already started implementing a browser like that but I can’t get rid of an impression that I’m reinventing the wheel.
Have you looked into JXPath? It lets you use XPath expressions to query and manipulate Java object graphs. The
JXPathContextclass lets you iterate over the values of selected nodes if you just want to extract the string values, or you can use theselectNodesmethod to get JDOM wrappers.For instance, I think your example query would look something like:
Unfortunately I haven’t actually worked with JXPath (though I’ve also tried implementing an XPath-like traverser before too), but apparently you can also configure it to automatically create objects for a particular path. I didn’t see any visitor functionality, but the
iterate,getValue, andsetValueshould be able to accomplish the same thing. You could also rig up a simple wrapper class to run the query, iterate through the nodes, and pass the values to your own visitor interface. Something like:There’s a pretty detailed JXPath user guide too.