3

我有一个输入 xml 和相应的 java 类,如下所示。

<Address>
  <name>name</name>
  <streetName>street</streetName>
<Address>

public class Address {
    private String name;
    //getter and setter here
}

public class Home extends Address {
    private String streetName;
    // getter and setter follows
}

我试图解组xml,如下所示

import com.thoughtworks.xstream.XStream;

public class Main {
    public static void main(String as[]) {
        XStream xstream = new XStream();
        String str = "<com.xstream.inheritance.Address> <name>name</name> <streetName>street</streetName>"
                + "</com.xstream.inheritance.Address>";
        Address address1 = (Address) xstream.fromXML(str);
        System.out.println(address1.getName());
    }
}

我在线程“main”中遇到异常说异常

com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field com.xstream.inheritance.Address.streetName
---- Debugging information ----
field               : streetName
class               : com.xstream.inheritance.Address
required-type       : com.xstream.inheritance.Address
converter-type      : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path                : /com.xstream.inheritance.Address/streetName
version             : null

为什么我得到这个异常?

4

2 回答 2

2

XML 缺少指向您的扩展类的“​​类”属性。所以输出会是这样的:

<com.xstream.inheritance.Address class="com.xstream.inheritance.Home">
 <name>name</name>
 <streetName>street</streetName>
</com.xstream.inheritance.Address>

这是由 XStream 自动完成的。

于 2012-06-08T09:56:45.320 回答
0

假设您的 bean 在包“com.xstream.inheritance”中,如果您将 xml 的根标记从

<com.xstream.inheritance.Address>

<com.xstream.inheritance.Home>

这是必要的,因为 streetName 字段仅在 Home 中可用,在 Address 中不可用。另请注意, fromXml() 正在返回一个 Home 实例,而不仅仅是一个地址。

于 2012-05-11T13:02:17.040 回答