【问题标题】:Can't encode INetAddress to xml无法将 INetAddress 编码为 xml
【发布时间】:2012-02-08 08:02:42
【问题描述】:

我正在尝试使用 java.beans.XMLEncoder 类将具有 INetAddress 类型成员的对象编码为 xml。不幸的是,我得到以下异常:

java.lang.IllegalAccessException:类 sun.reflect.misc.Trampoline 无法使用修饰符“”访问类 java.net.Inet4Address 的成员

这是我的代码:

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();
          }
       }
    }

}

【问题讨论】:

    标签: java xml xml-serialization xmlencoder


    【解决方案1】:

    javadoc for XmlEncoder 说:

    XMLEncoder 类是 ObjectOutputStream 的补充替代品,可用于生成 JavaBean [...]

    的文本表示

    (他们的重点)

    Inet4Address 不是 JavaBean,因此不适合以这种方式进行序列化。

    您必须使用不同的机制来实现您想要做的事情。 JAXB 框架included as part of java6 and above 是一个更健壮、更通用的 XML 序列化框架。

    【讨论】:

    • 非常感谢您的快速回答!
    【解决方案2】:

    您只需为Inet4Address 类安装一个持久性委托。改编自 Core Java Vol. 第 8 章中的示例。 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()});
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 2014-02-02
      相关资源
      最近更新 更多