Tuesday, November 13, 2007

Reflection in Java-XML binding frameworks

Almost all Java-XML binding frameworks use Java reflection to map Java objects to XML documents. I had used Castor and XMLBeans in our projects and were satisfied with the performance of both of them.

Recently a friend of mine told me that he had reservations on using Castor as it uses Reflection and hence cannot be used in high-performance applications. I contemplated on this and felt that some basic amount of reflection code would be present in any XML-binding framework; or how would the API call 'set' methods on Java objects during unmarshalling?

I found this discussion on the net that explains this same fact.

Snippet:
Castor will still use some amount of reflection (mainly to set values onto your domain objects) even if you are using a mapping file (a binding file is used during code generation only).

Having said that, let me add one thought. At the time most of these articles have been written (2001 to 2002), the use of reflection introduced some performance penalties, noticeable to some degree.

Since then, a lot of time and effort has gone into improving the JVMs/JDK/compilers to lessen this impact further and further. In my personal view, with the event of JDK 1.4 (and even more so with Java 5)
this problems have been addressed sufficiently in that I would not call the use of (moderate) reflection an issue any more. If use of reflection would still be an issue, frameworks like Spring and some of their most
powerful features (run-time AOP through Spring interceptors) would not have been adopted by the market as it happened in the last one or two years.

Btw, in case this is not clear enough, using a mapping file instead of Castor's 'introspector' to establish mappings between the Java domain classes and the XML artefacts does not really improve Castor's
performance, as both modes will cause Castor to use reflection to establish what methods to use on your Java objects to set a value, to get a value (from an instance variable) or to add a value to a collection member. Bear in mind that these activities happen at start-up time only, and thus once and once only.

At run-time, when e.g. unmarshalling an XML document to a predefined object hierarchy, Cstor will (and has to) use reflection to ...
a) create object instances (using Class.newInstance())
b) set and get values into/from your instance variables (Method.invoke())

No comments:

Post a Comment