Xstream中的继承问题

时间:2012-05-08 12:23:10

标签: xstream

我有一个输入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

为什么我得到这个例外?

2 个答案:

答案 0 :(得分:1)

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

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

这是由XStream自动完成的。

答案 1 :(得分:0)

假设您的bean位于包&#34; com.xstream.inheritance&#34;中,如果您从

更改xml的根标记,则您的Main类运行良好
<com.xstream.inheritance.Address>

<com.xstream.inheritance.Home>

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