package org.nhooo.example.bean; import java.beans.*; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; public class BeanToXmlTransient { private Long id; private String itemName; private String itemColour; private Integer itemQuantities; static { try { // 在此块中将更改属性的类型 // itemQuantities为瞬态,因此不会序列化 // 当我们使用XMLEncode将bean转换为xml时将其转换为xml // 持久性。 BeanInfo bi = Introspector.getBeanInfo(BeanToXmlTransient.class); PropertyDescriptor[] pds = bi.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { PropertyDescriptor propertyDescriptor = pds[i]; if (propertyDescriptor.getName().equals("itemQuantities")) { propertyDescriptor.setValue("transient", Boolean.TRUE); } } } catch (IntrospectionException e) { e.printStackTrace(); } } public static void main(String[] args) { BeanToXmlTransient bean = new BeanToXmlTransient(); bean.setId(new Long(1)); bean.setItemName("T-Shirt"); bean.setItemColour("Dark Red"); bean.setItemQuantities(new Integer(100)); try { XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream( new FileOutputStream("BeanTransient.xml"))); // 将指定对象的XML表示形式写入 // 输出。 encoder.writeObject(bean); encoder.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getItemColour() { return itemColour; } public void setItemColour(String itemColour) { this.itemColour = itemColour; } public Integer getItemQuantities() { return itemQuantities; } public void setItemQuantities(Integer itemQuantities) { this.itemQuantities = itemQuantities; } }
在这里将看到该itemQuantities属性未序列化为XML。
<?xml version="1.0" encoding="UTF-8"?> <java version="1.6.0_02"> <object> <void property="id"> <long>1</long> </void> <void property="itemColour"> <string>Dark Red</string> </void> <void property="itemName"> <string>T-Shirt</string> </void> </object> </java>