简体   繁体   中英

How to add functionality to JAXB unmarshalled objects?

I have an XML schema (.xsd file) from which I'm generating Java classes using JAXB. For many of the generated classes there are associated functions. For example, for generated class Dog there would be a function public static void bark(Dog) , and for generated class Cat there would be a function public static void meow(Cat) .

This feels weird in an object-oriented language like Java. What I would like would be to unmarshall XML into objects that include useful and relevant functionality rather than just being structs.

So if the generated classes are in package gen then I would have a different package with these classes:

public class Cat extends gen.Cat {
    public void meow() { ... }
}
public class Dog extends gen.Dog {
    public void bark() { ... }
}

Is there some way to unmarshall into these more-capable subclasses rather than into the gen.* classes?

The answer to this type of questions is usually "use or write an XJC plugin".

You can use the code injector plugin to add code to the generated classes, see this answer:

You can extend a class or implement an interface using the inheritance plugin from JAXB2-Basics:

Disclaimer: I'm the author of JAXB2-Basics.

From the design perspective schema-derived classes may be considered DTOs and in this case should not contain functionality. You'll need a business model then and use something like Dozer to map between DTOs and your business model classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM