我正在尝试使用 java.beans.XMLEncoder
类将具有 INetAddress 类型成员的对象编码为 xml。不幸的是,我得到以下异常:
java.lang.IllegalAccessException: Class sun.reflect.misc.Trampoline can not access a member of class java.net.Inet4Address with modifiers ""
这是我的代码:
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
XMLEncoder
class is a complementary alternative to the ObjectOutputStream and can used to generate a textual representation of a JavaBean [...]
(他们的重点)
Inet4Address
不是 JavaBean,因此不适合以这种方式进行序列化。
您必须使用不同的机制来实现您想要做的事情。 JAXB 框架,included as part of java6 and above , 是一个更健壮和通用的 XML 序列化框架。
关于java - 无法将 INetAddress 编码为 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9189593/