I have an XML file that has certain properties and mappings defined in it. These properties change very rarely. I don't want to reload and evaluate the properties/mappings every time I call use my jar file. Is there any way I can pre-compile my XML file into an object, so that the XML values get stored in the object? Whenever I change the XML file, if ever, I just need to recompile it once.
After you've read your XML data into an object you could write it to a file using Serialization and check next time, before you load your XML source whether it has been changed (by comparing their timestamps). In cases the XML source hasn't changed you could simply restore the configuration object by de-serialization from the file system.
You could just use a Java file to define these properties and mappings to begin with. No need to mess with XML if you aren't going to take advantage of loading changes to it without recompiling.
This might not be regarded as the best practice in the world... but if you're wanting to do this outside of any particular framework, you can always just use plain vanilla Java serialization. It's exactly what you're talking about... storing an object to disk (or whatever) and restoring it to memory later. Check out this tutorial if the subject is unfamiliar.
Couple a questions that might help you find an approach are:
- How big is your XML file?
- How long does it take for you to parse it and turn it into an object?
- Is it prohibitive to have this process (load + parse + convert to object) every time your library loads?
Spring does exactly this; you configure the context with XML and when you boot your application it loads, parses and creates the objects according to your configuration. I've been dealing with big XML files in Spring and I can say it's pretty fast - and considering it's only done once, at boot, it's hardly ever a problem.
Spring also has an alternative in which your configuration is actual code, but I'm guessing you want to stick to XML configuration.
Another approach is having a tool to read the XML, convert it to an object and then storing this object to a file using object serialization. You can then load this file as a de-serialized object.