views:

226

answers:

4

In the system which I'm currently developing I often have to navigate an object tree and based on its state and values take actions. In normal Java this results in tedious for loops, if statements etc... Are there alternative ways to achieve tree navigation, similar to XPath for XML? I know there is JXPath and OGNL, but do you know any other libraries for such purpose? Do you know any libraries which generate bytecodes for specific tree navigation expressions to make the processing as fast as Java native fors and ifs?

A: 

Jakarta collections ( http://commons.apache.org/collections/apidocs/ ) allow you to apply predicates, functors, etc... on collection members. Is this the direction you are looking for?

David Soroko
A: 

I think JXPath could be the solution you're looking for.

Riduidel
+1  A: 

Can I ask you why you would not like OGNL/JXPath ? Obviously you may have done your research to say no but I would like to know why OGNL is not solving a purpose that it was designed to solve.

Also google-collections has some functors (in addition to commons collections mentioned above) which may be worth looking at.

Calm Storm
OGNL and JXPath use reflection to interpret the graph or tree navigation expressions. In some situations this is ok, but for my use case I need a library which generates bytecodes for the tree expressions to make them as fast as normal java code.
lewap
+1  A: 

You may want to consider Jakarta Bean Utils

String street = (String) PropertyUtils.getProperty(user, "address.street");

You can navigate through the object graph using a dot notation. You can access also indexed properties. More details on the docs.

One drawback is that Bean Utils expects that the graph you are navigating does not contain null references.

The code snippet below would throw a NPE

Person person = new Person();
person.setAddress(null);

String street = (String) PropertyUtils.getProperty(person, "address.street");

To overcome this limitation my team implemented a class that creates instances of all null references of a graph on demand. This code is based on reflection and dynamic proxies (CGLIB).

Daniel Melo
That is true, but using the beanutils it is not possible to define predicates on nodes or execute functions on values.
lewap
I understand, I didn't capture that requirement. In that case David's suggestion (Common Collections) may be useful. It has a predicates API (http://www.discursive.com/books/cjcook/reference/collections-sect-filtering.html), but it may be more verbose than you would expect. You may also consider Google Collections (http://code.google.com/p/google-collections/). I overheard that they also implement filtering by predicates
Daniel Melo