users@jaxb.java.net

Plugin to change JAXB 2.0 default values behavior

From: Kohsuke Kawaguchi <Kohsuke.Kawaguchi_at_Sun.COM>
Date: Wed, 07 Sep 2005 21:59:38 -0700

Scott Allan wrote:
> I'm trying to build a plugin to add the default values from the schema
> to my bean.

Cool! Would you be interested in hosting that on jaxb2-commons? I'd be
very happy to add you as a developer so that you can commit.

> I can't seem to find an easy way to obtain the field that
> corresponds to the property without checking all of them. There is no
> getField() method that I can find. The field() methods all seem to be
> for creating new fields.

Good point. I guess FieldOutline can expose something like:

        JAnnotatable getAnnotatedProgramElement()

... which returns a JFieldVar or JMethod that has JAXB annotations on it
(or is it guaranteed to be always JFieldVar?) This would allow plugins
to put extra annotations on the same field.


The way element default is handled is somewhat unintuitive. The local
element like this

   <xs:element name="test" type="xs:string" default="testvalue"/>

... would actually become a CTypeRef. The default value of element is
set on CTypeRef. We can't use CPropertyInfo.defaultValue for this,
because sometimes XJC needs to generate things like:

        @XmlElemens({
          @XmlElement(name="a",type=String.class,defaultValue="abc"),
          @XmlElement(name="b",type=Integer.class,defaultValue="5"),
        })
        Object foo;

So if you search for the references of CPropertyInfo.defaultValue, right
now it is only used for attribute properties.

I think what you'd want to do with your plugin is to look for all
CElementProperty-s in the model, find those which only have one CTypeRef
in CElementProperty.getTypes(), propagate its CTypeRef.defaultValue to
CPropertyInfo.defaultValue.

The string default value can be turned into a JExpression by using
TypeUse.createConstant.


> There doesn't seem to be a way to display a JExpression once it has been
> set so I can't really check what is in there.

I think a toString method on JExpression would do a lot of good. Are you
interested in writing it :-) ?


> I see no way of accessing the schema org.w3c.dom Nodes for a class to
> check the default attribute except for when examining the plugin
> customizations. I don't want to annotate every element though.

The schema elements are not parsed into DOM. Instead you can use
CPropertyInfo.getSchemaComponent() to get to an XSOM object
(http://xsom.dev.java.net/) which exposes the SOM in much better way.

But I think in your case just looking at CTypeRef.defaultValue would be
suffice.


-- 
Kohsuke Kawaguchi
Sun Microsystems                   kohsuke.kawaguchi_at_sun.com