Using the "transient" keyword in a variable declaration or "@Transient" on a getter does not stop XMLEncoder from serializing properties. The only way I can say that XMLEncoder does not serialize certain properties is with code like:
BeanInfo info = Introspector.getBeanInfo(MyClass2.class); PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; ++i) { PropertyDescriptor pd = propertyDescriptors[i]; if (pd.getName().equals("props")) { pd.setValue("transient", Boolean.TRUE); } }
Really??? Is there an easier way that does not require code execution while all the properties are executing? Something like a transition modifier will swing!
Here's a JavaBean that will have all the properties serialized by XMLEncoder, despite using a "transient":
import java.io.Serializable; import java.beans.XMLEncoder; public class TestJavaBeanSerialization implements Serializable { public TestJavaBeanSerialization() {} private transient String myProp1 = null; private String myProp2 = null; @Transient public String getMyProp1() { return myProp1; } public void setMyProp1(String a) { myProp1 = a; } public String getMyProp2() { return myProp2; } public void setMyProp2(String a) { myProp2 = a; } public static void main( String[] args ) { TestJavaBeanSerialization myObj = new TestJavaBeanSerialization(); myObj.setMyProp1("prop 1"); myObj.setMyProp2("prop 2"); XMLEncoder encoder = new XMLEncoder(System.out); encoder.writeObject(myObj); encoder.close(); } }
Here's the output of this program:
<?xml version="1.0" encoding="UTF-8"?> <java version="1.6.0_29" class="java.beans.XMLDecoder"> <object class="TestJavaBeanSerialization"> <void property="myProp1"> <string>prop 1</string> </void> <void property="myProp2"> <string>prop 2</string> </void> </object> </java>
UPDATE
I still have not received a definitive answer to the original question. There is this article that people continue to refer, but it is not clear, and no one gave a link to the API or specification, which clearly states that the only way to mark a property as transient is to iterate over all the properties and call "setValue".
source share