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();
}
}
}
}
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.
You just need to install a persistence delegate for the Inet4Address
class. Adapted from an example in Chapter 8 of Core Java Vol. 2 :
e.setPersistenceDelegate(Inet4Address.class, new DefaultPersistenceDelegate() {
@Override
protected Expression instantiate(Object oldInstance, Encoder out) {
InetAddress old = (InetAddress) oldInstance;
return new Expression(oldInstance, InetAddress.class, "getByAddress",
new Object[]{old.getAddress()});
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.