Title: How do you mark a property as transient in a Javabean in order to avoid serialization by XMLEncoder?
Tags: java;javabeans
Question: Using the "transient" keyword on a variable declaration or "@Transient" on the getter does not stop the XMLEncoder from serializing properties.  The only way I've found to tell the XMLEncoder not to serialize specific 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 doesn't require runtime code to loop through all the properties?  Something like the transient modifier would rock!

Here's a JavaBean that will have all it's properties serialized by XMLEncoder, despite the use of "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 running this program:

```<?xml version="1.0" encoding="UTF-8"?&gt; 
<java version="1.6.0_29" class="java.beans.XMLDecoder"&gt; 
 <object class="TestJavaBeanSerialization"&gt; 
  <void property="myProp1"&gt; 
   <string&gt;prop 1</string&gt; 
  </void&gt; 
  <void property="myProp2"&gt; 
   <string&gt;prop 2</string&gt; 
  </void&gt; 
 </object&gt; 
</java&gt; 
```

UPDATE

I still have not received a definitive answer to the original question.  There's this article that people keep referencing, but it's not clear and no one's given a reference to an API or spec that clearly states the only way to mark a property as transient is to loop through all the properties and call "setValue".

Comment: You've posted your workaround...could you post the code that doesn't work?

Comment: Because the official JavaBeans tutorial says the transient property should work: http://docs.oracle.com/javase/tutorial/javabeans/advanced/persistence.html

Comment: BTW, I did not get my example from any official document... so what official document are you referring to?

Comment: Hmmm... I haven't read anywhere that the two are different.  But I guess that's the case.  I've read this article you give and I've read the java tutorial I posted a couple comments up.  I'd very much like to see an official document from Oracle explaining the differences between XMLEncoder and Java Object Serialization API.  It's unfortunate that such a document is not easily found, as it makes a lot of sense to use the "transient" modifier for XMLEncoder as well as ObjectOutputStream/ObjectInputStream.

Comment: The standard Java object serialization API is a language-level construct, and as such the transient keyword is only available to the compiler, snyderjasmine@example.net. As far as I can tell the XML serialization system is what they implemented upon realizing that the original API was terrible. Alas, like much of Java it is robust but very heavy on boilerplate code.

Comment: But like many annoying boilerplate-y things in Java, using Groovy can lend it a lot of brevity:

`def agentPD = Introspector.getBeanInfo(this).propertyDescriptors.find { it.name == "agent" }
        agentPD.setValue("transient", Boolean.TRUE)`

;)

Comment: A @Transient annotation would be available at runtime just fine. There's no explanation along the lines of "it can't be done"

Comment: I agree with @BogdanCalmac, the Transient annotation (from java.beans) has the same effect than FeatureDescriptor.setValue("transient", Boolean.TRUE).

Comment: Given that you seem to have obtained this code from the official documentation site, why would you expect there to be another method for excluding properties from serialization?

Comment: You are mixing up standard serialization with XMLEncoder serialization - http://java.sun.com/products/jfc/tsc/articles/persistence4/#transient


Here is another answer: I was accustomed to use this known solution for several years in my own code but there is a much more simple one since Java 1.7: the java.beans.Transient annotation. Note that you can use it on the getters and the setters but not on the fields unlike javax.persistence.Transient (JPA).

```import java.beans.Transient;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

public class Test {

public static final void main(String[] args) throws Throwable {
    final Capsule caps = new Capsule();
    caps.setIdentifier("6545346");
    caps.setMe("Julien");
    caps.setSentences(new ArrayList<&gt;(Arrays.asList(new String[]{"I don't like my job","I prefer sleeping"})));
    try (FileOutputStream fOut = new FileOutputStream(new File(System.getProperty("user.home"), "test.xml")); 
         BufferedOutputStream out = new BufferedOutputStream(fOut);
         XMLEncoder encoder = new XMLEncoder(out)) {
        encoder.writeObject(caps);
        encoder.flush();
    }
}

public static final class Capsule {

    private String identifier;

    private transient String me;

    private transient ArrayList<String&gt; sentences;

    public Capsule() {
        super();
    }

    @Transient
    public ArrayList<String&gt; getSentences() {
        return sentences;
    }

    @Transient
    public void setSentences(ArrayList<String&gt; sentences) {
        this.sentences = sentences;
    }

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    @Transient
    public String getMe() {
        return me;
    }

    @Transient
    public void setMe(String me) {
        this.me = me;
    }
}}
```

The result is:

```<?xml version="1.0" encoding="UTF-8"?&gt;
<java version="1.7.0_76" class="java.beans.XMLDecoder"&gt;
 <object class="Test$Capsule"&gt;
  <void property="identifier"&gt;
   <string&gt;6545346</string&gt;
  </void&gt;
 </object&gt;
</java&gt;
```

Note the absence of the transient values. I couldn't skip the collections in 2009 but it seems to work now.


Here is another answer: You use the wrong @Transient

Should use java.beans.Transient for the annotation.  javax.persistence.Transient is only respected in the context of database persistence, not BeanInfo serialization.


Here is another answer: I had a similar problem and I was looking for an easier solution. The way I managed it is by breaking Java Beans conventions. 

If you don't want to serialize a field, don't set getters setters for it. Instead of "get" and "set", use other prefixes like "retrieve" and "save". For example -

```int x=0;
public int retrieveX() {
    return x;
}
public void saveX(int x) {
    this.x = x;
}
```

This did the trick for me and I'm sure will help others who don't specifically need Java Beans conventions in the code. Using this way makes the variable available throughout your application but at the same time hiding it from XMLEncoder serializer.

Hope it helps someone in future.

Comment for this answer: I like this idea and +1'd it, but it is difficult to bring myself to use this method as it will require that I remember the method is called `retrieveX()` years after I wrote it.  I don't think that's likely.

Here is another answer: this is the only way that declare properties is transient.you can see the article. Url is http://www.oracle.com/technetwork/java/persistence4-140124.html?ssSourceSiteId=otncn#transient

Comment for this answer: where is the '@Transient' from?why i compile error and display 'Transient cannot be resolved to a type'
Comment for this answer: your class may implements Externalizable interface,then you provide implementations for both readExternal and writeExternal method.In writeExternal method you can  serialize specific properties.
Comment for this answer: This is an article, it does not say that the only way to mark a property as transient is with setValue("transient", Boolean.TRUE);.  Furthermore, the tutorial explicitly says: "Selectively exclude fields you do not want serialized by marking with the transient (or static) modifier."  The tutorial can be found at: http://docs.oracle.com/javase/tutorial/javabeans/advanced/persistence.html
Comment for this answer: Sorry, the @Transient is provided by import javax.persistence.Transient;
Comment for this answer: What is the difference?
Comment for this answer: @Jason You make a confusion between the bean persistence and the long term persistence. Jax jiang, this annotation is available since Java 1.7.

Here is another answer: A workaround might be to use JAXB as your XML serializer which is bundled with Java 1.6. It supports an @XmlTransient annotation. 


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 6, 'CommentCount': 10, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2012:00:01/11/12', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><javabeans>', 'Title': 'How do you mark a property as transient in a Javabean in order to avoid serialization by XMLEncoder?', 'ViewCount': 7258, 'id': 8813631, 'user_AboutMe': '<p>I\'m a freelance software developer, <a href="http://insilicalabs.com" rel="nofollow noreferrer">for hire</a>.  I specialize in scientific software and web applications.  Some of the projects I have completed involve</p>\n<ul>\n<li>developing tools to simulate and optimize mathematical models of biological systems, and</li>\n<li>building web sites for online instructional videos.</li>\n</ul>\n', 'user_AccountId': 149396.0, 'user_DisplayName': 'Jason', 'user_Reputation': 11184.0, 'user_Views': 850.0, 'user_id': 361855.0}}