Presents your
JAVA E-NEWSLETTER for April 8, 2004
<------------------------------------------->
SERIALIZING OBJECTS WITH XSTREAM
XML isn't the panacea that its evangelists claimed it would be, but it
does have a place in IT and will be around for a long time.
Configuration files are popular (though not) glamorous uses of XML
schemas (XMLS). For the corporate programmer, XML config files aren't
as accessible as they should be. Even though XML is just text, the
overhead necessary to parse the XML is usually too high a price to pay
for smaller applications. Well, now there's XStream.
XStream isn't a config file parser by trade. In the words of its
creators, XStream is "a simple library to serialize objects to XML and
back again." As soon as I saw it, I knew it solved at least one of my
long-running problems. It's a perfect fit for parsing and writing
small, simple XML files a la config files.
Here's a simple example to show how you could use XStream to read a
configuration file for a fictitious application that needs to know a
server's location.
The config file looks like this:
1080
localhost
The code for reading the XML and creating the AuthServer config object
looks like this:
XStream xs = new XStream();
xs.alias("authServer", AuthServerConfig.class);
AuthServerConfig asc = (AuthServerConfig) xs.fromXML(xml);
The above code looks too good to be true, but it's not. XStream doesn't
have any external dependencies; it doesn't require an XML parser; it
doesn't need mapping files, and so on. XStream 1.0 isn't released yet,
but it's open source, so you can give it a once-over before committing.
If you're looking for a simple way to get your objects out of XML or
vice versa, it's worth your time to take a look at XStream and see if
it's useful to you.
http://xstream.codehaus.org/
Here's an example of related code:
import java.util.Date;
import com.thoughtworks.xstream.XStream;
public class XStreamTip {
private static String xml =
""
+ " 1080"
+ " localhost"
+ "";
public static void main(String []args) {
XStream xs = new XStream();
xs.alias("authServer", AuthServerConfig.class);
AuthServerConfig asc = (AuthServerConfig) xs.fromXML(xml);
System.out.println(asc);
System.out.println(xs.toXML(asc));
}
}
class AuthServerConfig {
private int port;
private String server;
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return this.port; }
public void setServer(String server) {
this.server = server;
}
public String getServer() {
return this.server;
}
}
David Petersheim is the Director of Application Development with
Genscape, Inc. He designs and develops server-side applications to
acquire and process real-time energy data.
----------------------------------------