Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object tree navigation language in Java

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?

like image 589
paweloque Avatar asked Mar 08 '10 10:03

paweloque


2 Answers

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).

like image 173
Daniel Melo Avatar answered Oct 20 '22 00:10

Daniel Melo


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.

like image 43
Kannan Ekanath Avatar answered Oct 20 '22 01:10

Kannan Ekanath