I'm trying to implement the builder pattern for generating Apache XmlBeans objects.
I've generated builders for all my classes, which inherit from:
public abstract class Builder<T extends XmlObject> {
protected T xmlObject;
@SuppressWarnings("unchecked")
public T build() {
return (T) xmlObject.copy();
}
}
Then I've created several builders like this one (Time2Save inherits from XmlObject):
public class Time2SaveBuilder extends Builder<Time2Save> {
public Time2SaveBuilder(int amount, String unit) {
xmlObject = Time2Save.Factory.newInstance();
xmlObject.setUnit(unit);
xmlObject.setValue(amount);
}
}
It works perfectly fine. But the problem I have is that I don't really like the duplication of having to instantiate the xmlObject in each builder, and I'd rather do it in the abstract Builder class if possible. So I've tried adding this constructor to the Builder class:
@SuppressWarnings("unchecked")
public Builder() {
xmlObject = (T) T.Factory.newInstance();
}
And leaving the implementations like this:
public class Time2SaveBuilder extends Builder<Time2Save> {
public Time2SaveBuilder(int amount, String unit) {
xmlObject.setUnit(unit);
xmlObject.setValue(amount);
}
}
The problem is that I get the following error:
Exception in thread "main" java.lang.ClassCastException:
org.apache.xmlbeans.impl.values.XmlAnyTypeImpl cannot be cast to
a.b.c.d.Time2SaveDocument$Time2Save
I think XmlAnyTypeImpl
is the result of calling the static XmlObject.Factory
instead of one from the inheriting class (in this case, Time2Save
). I'd like to know why this is happening (since I'm calling T.Factory
and not XmlObject.Factory
) and if there's any way to do this without duplicating the Factory call in each builder implementation. Thanks!