我该如何扩展由JAXB,CXF或Hibernate工具生成的Java代码? [英] How can I extend Java code generated by JAXB, CXF or Hibernate tools?

查看:110
本文介绍了我该如何扩展由JAXB,CXF或Hibernate工具生成的Java代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

生成的Java源代码,如使用Hibernate工具生成的代码生成的代码


  • 与JAXB模式绑定(xjc)

  • 使用WDSL2Java(cxf)生成的代码



类是价值对象类型,没有业务逻辑。如果我向生成的源代码添加方法,如果我重复源代码生成,我将放弃这些方法。



这些Java代码生成工具是否提供了扩展生成的代码?/ b>

例如,用于覆盖ToString方法的


  • (用于日志)
  • 实现访问者模式(用于数据分析/验证)

    解决方案

    对于JAXB,请参阅添加行为



    基本上,您将JAXB配置为返回您通常期望的对象的自定义实例。在下面的示例中,您将创建一个扩展了JAXB对象Person的新对象PersonEx。这个机制很好,因为你是从生成的类派生出来的,并且根本不会改变JAXB类或模式。

      package org.acme.foo.impl; 
    $ b $ class PersonEx extends Person {
    @Override
    public void setName(String name){
    if(name.length()< 3)throw new IllegalArgumentException( );
    super.setName(name);



    @XmlRegistry
    class ObjectFactoryEx扩展ObjectFactory {
    @Override
    Person createPerson(){
    return new PersonEx();


    $ / code>

    请注意,@Override指令非常重要, JAXB对象的变化 - 它会阻止你的定制成为孤立的。


    With generated Java source code, like

    • code generated with Hibernate tools
    • code generated with JAXB schema binding (xjc)
    • code generated with WDSL2Java (cxf)

    all generated classes are "value object" types, without business logic. And if I add methods to the generated source code, I will loose these methods if I repeat the source code generation.

    Do these Java code generation tools offer ways to "extend" the generated code?

    For example,

    • to override the ToString method (for logging)
    • to implement the visitor pattern (for data analysis / validation)

    解决方案

    For JAXB, see Adding Behaviours.

    Basically, you configure JAXB to return a custom instance of the object you'd normally expect. In the below example you create a new object PersonEx which extends the JAXB object Person. This mechanism works well in that you're deriving from the generated classes, and not altering the JAXB classes or schemas at all.

    package org.acme.foo.impl;
    
    class PersonEx extends Person {
      @Override
      public void setName(String name) {
        if(name.length()<3) throw new IllegalArgumentException();
        super.setName(name);
      }
    }
    
    @XmlRegistry
    class ObjectFactoryEx extends ObjectFactory {
      @Override
      Person createPerson() {
        return new PersonEx();
      }
    }
    

    Note that the @Override directive is important in case your JAXB object changes - it will prevent your customisation becoming orphaned.

    这篇关于我该如何扩展由JAXB,CXF或Hibernate工具生成的Java代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆