开发者

How to add custom behaviors to JAXB generated classes. Custom not overriding existing methods

I got an xsd from an external source over which i have no control. Now we want to add custom methods to the JAXB generated classes so that t开发者_如何学JAVAhe object would know more about itself rather than being a simple POJO with getters and setters.

The idea is like once we implement this type of approach we don't need to drill down the hydrated object but ask the object for specific information that we need through calling the custom methods and could get what we want?

Of course there is the traditional programming approach where in i keep on drilling down the children of children children of the root object, calling getter methods on each child and implementing business logic. But somehow the team here doesn't want it that way.

One approach I have done so far is brute force one. Like i generate classes from XSD using JAXB. then i have an external utility (right now this is a stand alone java program) which when run, will read some text files (structured in our own way to find out which method should go and into which .java file) in a specific directory which holds the custom methods, and move those methods to appropriate JAXB generated classes. Every time i get a new version of XSD i need to generate classes, invoke this utility and perhaps resolve some compilation issues etc in case there are some variable changes in JAXB generated classes. The utility is working perfectly fine. But i want to know this.

Is there any better way to do this? I checked the internet. There are some solutions given but those are just overriding the existing get methods in the JAXB generated objects and not adding completely new methods.

Please suggest.


Well, the "cleanest approach" would be using Aspect Oriented programming (AOP) which does what you describe not on source code level but at runtime. It injects methods into classes. One possible implementation of AOP is AspectJ

A second alternative that would be possible if the XML shema is not too complex is creating a wrapper around it.

The third alternative you have already described. But I thing you can rely on standard tools instead of coding something yourself - I would suggest to use the standard diff/patch tools for that. As long as your code style is fixed it is not too complicated to create a diff from an existing modified java file and apply it on the freshly generated JAXB code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜