2014-09-12 62 views
0

有人可以向我解釋writer.toString如何保存客戶數據嗎?看起來,元帥(客戶,作家)以某種方式修改了作者。下面請看,感謝:StringWriter如何採取新的價值?

Customer customer = new Customer(); 
customer.setId(42); 
customer.setName("Bill Burke"); 
JAXBContext ctx = JAXBContext.newInstance(Customer.class); 
StringWriter writer = new StringWriter(); 
ctx.createMarshaller().marshal(customer, writer); 

[在這裏看到:]

String custString = writer.toString(); // how did writer suddenly take on value? 

customer = (Customer)ctx.createUnmarshaller() 
      .unmarshal(new StringReader(custString)); 

回答

2

的StringWriter是一個作家的實現,寫入到一個StringBuffer。當你調用write()時,你追加到那個StringBuffer。 ToString()在該StringBuffer上調用toString()並返回它。 Marshaller.marshal()只是將JAXB對象序列化爲XML,並將它們寫入Writer(從而寫入StringBuffer)。然後,第二個片段中的StringReader將從StringBuffer創建的字符串中讀取數據。