users@jaxb.java.net

Re: Edit the generated Code

From: Aleksei Valikov <valikov_at_gmx.net>
Date: Mon, 16 Oct 2006 18:03:35 +0200

Hi.

> Thanks for your response.
> I don't get what you mean with your 1st solution. Generate with
> addons/plugins?

Yes. We generate a lot of additional code with plugins.

> And for your 2nd, I found it's not be able to be used in my case. While
> the XSD file itself keeps changing. So I can't just subclass my own
> class to the generated code. If the xsd file changes, and new Codes
> generated, all the extension will be gone.

I am not sure if you got the idea. I'm talking about subclassing your own
classes with JAXB-generated code, not vice versa.

Ok, here's simple an example for you. Imagine you have a user type with first
name and family name and you want to have an extension method which returns the
name as first name plus last name.

First you write an AbstractUserType like this:

public class AbstractUserType
{
        public abstract String getFirstName();
        public abstract String getLastName();

        public String getName() { return getFirstName() + " " + getLastName(); }
}

Then in your schema you define something like

<complexType name="userType">
<!-- This is a customization for the inheritance plugin -->
        <annotation><appInfo><i:extends="com.foo.AbstractUserType"/></appInfo></annotation>
        <sequence>
                <element name="firstName" type="string"/>
                <element name="lastName" type="string"/>
        </sequence>
</complexType>

JAXB (+ plugin) will produce UserType extends AbstractUserType. Getters for
firstName and lastName elements will implement abstract methods from
AbstractUserType. The generated UserType class will have the extension
functionality (getName()) you'd like it to have.

This approach is not vulnerable to schema changes. You don't have to manually
add the extension code, it's simply inherited.

> In my project, I'm creating an API of a system (The system itself would
> be translated to schema file, which later be used by JAXB to generate
> the Java codes.
> So I would like to wrap/package the generated code with functionality
> which is allowed in this API. In this way, it would also protecting the
> lost of functionality when new features were added to the system. So I'm
> wondering the best way to do this.
> Any advice?

That's exactly how I do it. In my projects, I define abstract classes/interfaces
which then get implemented/extended by JAXB generated code. My business code
takes advantage of the extensions I've defined in the abstract classes. New
features of the schema do not require me to adapt extensions. Adaptions are only
required if schema changes are backwards-incompatible, but this requires manual
corrections in any case.

Bye.
/lexi