How can I extend Java code generated by JAXB, CXF or Hibernate tools?

mjn picture mjn · Apr 23, 2009 · Viewed 13k times · Source

With generated Java source code, like

  • code generated with Hibernate tools
  • code generated with JAXB schema binding (xjc)
  • code generated with WDSL2Java (cxf)

all generated classes are "value object" types, without business logic. And if I add methods to the generated source code, I will loose these methods if I repeat the source code generation.

Do these Java code generation tools offer ways to "extend" the generated code?

For example,

  • to override the ToString method (for logging)
  • to implement the visitor pattern (for data analysis / validation)

Answer

Brian Agnew picture Brian Agnew · Apr 23, 2009

For JAXB, see Adding Behaviours.

Basically, you configure JAXB to return a custom instance of the object you'd normally expect. In the below example you create a new object PersonEx which extends the JAXB object Person. This mechanism works well in that you're deriving from the generated classes, and not altering the JAXB classes or schemas at all.

package org.acme.foo.impl;

class PersonEx extends Person {
  @Override
  public void setName(String name) {
    if(name.length()<3) throw new IllegalArgumentException();
    super.setName(name);
  }
}

@XmlRegistry
class ObjectFactoryEx extends ObjectFactory {
  @Override
  Person createPerson() {
    return new PersonEx();
  }
}

Note that the @Override directive is important in case your JAXB object changes - it will prevent your customisation becoming orphaned.