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

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

问题描述

使用生成的Java源代码,如

With generated Java source code, like

  • 使用 Hibernate 工具生成的代码
  • 使用 JAXB 模式绑定 (xjc) 生成的代码
  • 使用 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.

这些 Java 代码生成工具是否提供扩展"生成代码的方法?

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

例如

  • 覆盖 ToString 方法(用于日志记录)
  • 实现访问者模式(用于数据分析/验证)

推荐答案

对于 JAXB,请参阅 添加行为.

For JAXB, see Adding Behaviours.

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

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();
  }
}

请注意,@Override 指令很重要,以防您的 JAXB 对象发生更改 - 它会防止您的自定义成为孤立.

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天全站免登陆