Preventing a Bean Property from Being Serialized to XML
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
MyClass o = new MyClass();
o.setProp(1);
o.setProps(new int[] { 1, 2, 3 });
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
encoder.writeObject(o);
encoder.close();
}
}
class MyClass {
int i;
public int getProp() {
return i;
}
public void setProp(int i) {
this.i = i;
}
int[] iarray = new int[0];
public int[] getProps() {
return iarray;
}
public void setProps(int[] iarray) {
this.iarray = iarray;
}
static {
try {
BeanInfo info = Introspector.getBeanInfo(MyClass.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);
}
}
} catch (IntrospectionException e) {
}
}
}
Related examples in the same category