Search code examples
javaxmlxml-serializationxmlencoder

Can't encode INetAddress to xml


I'm trying to encode an object that has a member of type INetAddress to xml using the java.beans.XMLEncoder class. Unfortunately, I get the following exception:

java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class java.net.Inet4Address with modifiers ""

Here is my code:

public class INetAddressFoo {

   private InetAddress addr;

   public INetAddressFoo() {
   }

   public InetAddress getAddr() {
      return addr;
   }

   public void setAddr(InetAddress addr) {
     this.addr = addr;
   }
}

public class Test{

    public static void main() throws Exception  {
        INetAddressFoo foo = new INetAddressFoo();
        InetAddress addr = InetAddress.getByName("localhost");
        foo.setAddr(addr);
        File file = new File("inet.xml");

        XMLEncoder encoder = null;

       try {
          encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(file)));
          encoder.writeObject(t);
       } finally {
          if (encoder != null) {
             encoder.close();
          }
       }
    }

}

Solution

  • The javadoc for XmlEncoder says:

    The XMLEncoder class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean [...]

    (their emphasis)

    Inet4Address is not a JavaBean, and therefore is not suitable for serializing in this way.

    You'll have to use a different mechanism to achieve what you're trying to do. The JAXB framework, included as part of java6 and above, is a more robust and general XML serialization framework.