2012-05-08 92 views
2

我有一個輸入xml和相應的java類,如下所示。Xstream中的繼承問題

<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 
} 

我試着解組像下面

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

我得到一個異常說螺紋 異常「主要」

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 

爲什麼我得到這個異常的XML?

+2

我看到你從未批准任何問題的答案。你應該正式批准你認爲正確的答案。有關詳細信息,請參閱http://meta.stackexchange.com/a/65088。 – Pino

回答

1

XML缺少指向擴展類的「​​class」屬性。所以輸出會是這樣的:

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

這是由XStream自動完成的。

0

假設你的豆是在包「com.xstream.inheritance」,主類,如果你從

<com.xstream.inheritance.Address> 

更改XML的根標籤

<com.xstream.inheritance.Home> 

效果很好這是必要的,因爲streetName字段只能在Home中使用,而不能在Address中使用。還要注意fromXml()返回一個Home實例,而不僅僅是一個地址。