Search code examples
jaxbvisitor-patterngenerated-codecustomising

How can I make JAXB-generated classes participate in a Visitor pattern?


Hey folks, hopefully a nice easy one here.

I'm generating classes with JAXB from a schema, and I'd like to be able to process them with a Visitor pattern.

To do that, I think I need every JAXB-generated class to implement the interface I've defined, and add a very simple method to them, so a simple example would be:

Default class:

public class MyClass {
   private String name;

   public void get/setName() {...}
}

Desired class:

public class MyClass implements MyVisitorNode {
  private String name;

  public void get/setName() {...}

  public void accept(MyVisitorVisitor visitor) {
    visitor.visit(this);
  }
}

Is this possible, and if it is, what are the options? (Change the schema, runtime bytecode manipulation, manipulate the JAXBContext somehow...)

Ideally, without relying on vendor-specific extensions.

Thanks!


Solution

  • The xjc compiler for JAXB has a plugin interface that allows developers to create plugins that modify the generated code. My personal favorite is the fluent-api but there are others to add toString, equals, hashCode, etc.

    I created a plugin using this technology to implement the visitor pattern and made it available as a google code project. It may not be exactly what you're looking for but it might be a good place to start to review the code and tests if you need to modify it to suit your needs.

    http://code.google.com/p/jaxb-visitor/