简体   繁体   English

向JAXB生成的类添加行为

[英]Adding behaviour to JAXB generated class

I have to add little bussiness logic in my jaxb generated classes. 我必须在jaxb生成的类中添加一些业务逻辑。 For example, I have following XMLs: 例如,我有以下XML:

<vehicle>
 <car id="20" make="ABC"/>
</vehicle>

<vehicle>
 <motorcycle id="05" make="XYZ"/>
<vehicle>

<vehicle>
 <truck id="34"  make="UVW"/>
</vehicle>

And I generate XSD for these. 我为此生成了XSD。

Now what I have to achieve is during unmarshalling of any XML of these type (that is whenever setters of car, motorcycle or truck is envoked, it should also set the vehicle type which I don't want to add as an attribute in the XML). 现在,我需要实现的是在解组这些类型的任何XML时(也就是说,每当调用汽车,摩托车或卡车的设置者时,它也应该设置我不想添加为XML中的属性的车辆类型)。

Or after unmarshalling (any way by which I can know the QName of sub element). 或在解组后(我可以通过任何方式知道子元素的QName)。 I have tried How can I extend Java code generated by JAXP-cxf or Hibernate tools? 我已经尝试过如何扩展JAXP-cxf或Hibernate工具生成的Java代码? , but the overriden setters were never called. ,但从未调用覆盖的设置器。

JAXB has a "post construct" facility (see javadoc ). JAXB有一个“后构造”工具(请参阅javadoc )。 Just add something like this to your annotated class: 只需在您的带注释的类中添加以下内容即可:

void afterUnmarshal(Unmarshaller, Object parent) {
    vehicle.setType(..); // your logic here    
}

You can create a JAXB extension . 您可以创建一个JAXB扩展 But that sounds like an overhead to me - you could simple invoke an initializer whenever you unmarshal a JAXB object. 但这听起来像是我的开销-每当您解组JAXB对象时,都可以简单地调用一个初始化程序。 Something like: 就像是:

public class Initializer {
    public static void initialize(Vehicle vehicle) {
       vehicle.setType(..); // your logic here
    }
}

And call Initializer.initialize(unmarshalledObject) 并调用Initializer.initialize(unmarshalledObject)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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