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

1.5k views Asked by At

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!

2

There are 2 answers

0
massfords On BEST ANSWER

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/

0
Kris Babic On

The JAX-B generated classes are standard Java classes that you can customize in any way you desire, e.g., extend interface, add additional methods, etc..). The annotations on the class and attributes are the driving factor for the marshalling and unmarshalling process.

With that said, there are somethings you need to take into account if you customize the JAXB generated classes. As stated at the top of each class "Any modifications to this file will be lost upon recompilation of the source schema". In short, if you customize the class, you will need to manually make code changes to support any schema updates. If you do regenerated the classes, your custom code will be removed and you will have to start all over.