Java

Basic Reflection Magic, and BeanUtils too

In my current project, a good deal of my daily work goes into an often repeated sequence of tasks:

  • Read data from an XML file (so-called “structured content”, OpenCms)
  • Put the data into an object tree in order to do stuff with it
  • Put the object(s) on a JSP page context in order to display parts or all of the contained data.

The old way was a bit less comfortable, being heavily based on Maps and Lists that were filled with single elements of the structured content and that then had to be parsed a second time in the JSP. I like the use of transfer objects a lot better because it keeps the code clean and easy to maintain and because it’s easier to apply modifications to the data between reading it and displaying it.

Thus, I’m searching for a nice way to get the cleanest, most concise code for the XML -> object tree step. For simple tasks, I make havy use of BeanUtils at the moment. Let’s say the XML contains elements called “title”, “link” and “image”. I then create a class with exactly the same attributes and sensible types (in this case, they are all Strings, but I do use boolean and numeric values in some places).

Because the attribute names in the class are the same as they are in the XSD, respective XML file, I can then easily populate an instance of my class while reading from the XML at the same time, roughly like this:

PropertyDescriptor[] propertyDescriptors = 
    PropertyUtils.getPropertyDescriptors(Teaser.class);
 
Teaser teaser = new Teaser();
 
for (PropertyDescriptor pD : propertyDescriptors) {
    try {
        String xmlPath = /* create basic XPath here */ + pD.getName();
        BeanUtils.setProperty(
            teaser,
            pD.getName(),
            document.getStringValue(cmsObject, xmlPath, currentLocale)
	);
    } catch(...) {} /* Exception handling and logging omitted for brevity */
}

This code is partially specific to the OpenCms API, but I think you get the point.

In most situations, you would probably get the PropertyDescriptor array only once and put it into a constant, because it’s not very likely that the transfer class will change during runtime.

This way of saving about n-1 lines of code where n equals the number of attributes you want to read from the XML makes me very happy.

But, as with every solution, I’m still looking to improve this even more. The downside at the moment is that I cannot remove loops yet for lists of entries in nested XML files. Thus, I did some research + experimenting on reflection mechanisms today. My intention: to pass the top-level transfer class into a method that recursively checks the structure (e.g. dives down into lists of other custom transfer classes, e.g. List or whatever) of my desired object tree and that then goes ahead and slurps the entire XML into an object tree. This should – in the end – fit into only a couple lines of code, allowing for a clean API and perfect encapsulation of reusable “please-read-this-XML” code.

First experiments were quite successful and I recommend this article: Java Reflection: Generics, especially section 4, “Generic Field Types”.

I’ll omit my code snippets here, because it’s much more fun to build stuff like this yourself ;-)

I’m quite fascinated by the inner workings of reflection at the moment, and I suppose that I will research this topic until I have a working bit of code – only to then find some proven framework that does the same thing – but maybe my small, self-made solution is just so small and simple that it does NOT require me to put an extra 10 JARs into the project… or maybe the idea turns out to be complete crap – we will see. Essentially, it’s all about having fun with technology :-)

I’ll write a follow-up as soon as I have new results. Stay tuned!

Tags:

Wednesday, May 6th, 2009 Development, Technology No Comments

Carol McDonald

I’ve been reading Carol McDonald’s Blog for some weeks now. She is a Java Technology Evangelist at Sun Microsystems. She has a pretty impressive career summary:

Before returning to Sun in 2007, Carol worked 2 1/2 yrs as an Architect on massive OLTP Spring/hibernate application to manage > 10 mill loans for the consumer credit division of a leading automoblile manufacturer and a leading bank. Before joining Sun the first time in 1999 Carol worked on Pharmaceutical Intranet applications for Roche in Switzerland, a Telecom Network Management Application for Digital (now HP) in France, a X.400 Email Server for IBM in Germany, and as a student intern for the National Security Agency. Carol holds a M.S. in Computer Science from the University of Tennessee, a B.S. in Geology from Vanderbilt University, and is a Sun Certified Java Architect and Java Language Programmer.

I first stumbled across her blog reading the “MySQL for developers” article, which was a really nice piece of information. Right now, she is reporting about REST using Dojo, JAX-RS and Comet – sounds very interesting. Take a look :-)

Tags:

Friday, October 31st, 2008 Recommended Readings No Comments

Welcome!

Have fun reading this blog. You will find some "about" data if you follow the link in the header.

Archives