[英]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. 我正在尝试使用
java.beans.XMLEncoder
类将具有INetAddress类型的成员的对象编码为xml。 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 ""
java.lang.IllegalAccessException:类sun.reflect.misc.Trampoline无法使用修饰符“”访问类java.net.Inet4Address的成员
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: XmlEncoder
的Javadoc说:
The
XMLEncoder
class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean [...]XMLEncoder
类是ObjectOutputStream的补充替代方法,可用于生成JavaBean的文本表示形式。
(their emphasis) (重点)
Inet4Address
is not a JavaBean, and therefore is not suitable for serializing in this way. Inet4Address
不是JavaBean,因此不适合以这种方式进行序列化。
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.
作为Java6及更高版本的一部分包含的JAXB框架是一个更健壮和通用的XML序列化框架。
You just need to install a persistence delegate for the Inet4Address
class. 您只需要为
Inet4Address
类安装一个持久性委托。 Adapted from an example in Chapter 8 of Core Java Vol. 改编自《 Core Java Vol》第8章中的示例。 2 :
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()});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.