JAXB constructor injection
I would like to know how I can make the JAXB compiler make certain elements in my XML schema be declared as final in the java class definition and I would also like to be able to control the different constru开发者_Go百科ctors, as in I would like a constructor that could create the object with a full list of parameters contained in the class as well as the default private constructor needed by JAXB.
Any help?
Thanks.
Here is an example of what I am trying to do:
<xs:complexType name="mycomplex">
<xs:all>
<xs:element name="myboolean" type="xs:boolean"/>
</xs:all>
</xs:complexType>
now the generated code will look something like
public class mycomplex
{
protected boolean myboolean;
public boolean getMyboolean() { return myboolean; }
public void setMyboolean(boolean b) { this.myboolean = b; }
}
but I would like to edit the schema to make it look like:
public class mycomplex
{
protected final boolean myboolean;
public mycomplex(boolean b) { this.myboolean = b; }
public boolean getMyboolean() { return myboolean; }
}
Can this be achieved?
There isn't a standard JAXB way to generate a class that looks like that, because the JAXB spec doesn't support mapping to a class like that.
You could use the following code to avoid having a set method. You can add additional constructors if you want as long as there is a public default one.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlAccessorType(XmlAccessType.FIELD)
public class mycomplex
{
protected final boolean myboolean;
public boolean getMyboolean() { return myboolean; }
}
If you want to use the class that you described above with a non-default constructor and a field marked final you will need to create an XmlAdapter:
- http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
I have resolved this in another way. I am creating a tool that will edit the java source code files produced and will add in/remove what I need. Refer to this for more information: Using the Eclipse AST
I have similar problem and I found the following library: http://simple.sourceforge.net/download/stream/doc/tutorial/tutorial.php#immutable
And everything seems so simple now ;)
精彩评论