Customizing PropertySuppressionStrategy to use Java 5 Annotations
Suppose we want to mark properties to be serialized with Java 5 @Persistent annotation. So our bean code will look somewhat like this:
public class Person {
private String name;
@Persistent
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is one way of doing that
First define annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public static @interface Persistent {
}
Then replace the default PropertySuppressionStrategy with our custom one:
beanWriter.getXMLIntrospector().getConfiguration().setPropertySuppressionStrategy(new PropertySuppressionStrategy() {
@Override
public boolean suppressProperty(Class classContainingTheProperty, Class propertyType, String propertyName) {
boolean res = true;
PropertyDescriptor[] pds;
try {
pds = Introspector.getBeanInfo(classContainingTheProperty).getPropertyDescriptors();
} catch (IntrospectionException e) {
throw new Error(e);
}
for (int i = 0; i < pds.length; i++) {
if (pds[i].getName().equals(propertyName) && pds[i].getReadMethod().isAnnotationPresent(Persistent.class)) {
res = false;
break;
}
}
return res;
}
});