Generate constants for class attributes with maven?

旧街凉风 提交于 2019-12-06 05:19:34

Modifying existing class is more difficult then creating new one.

JPA took a interesting approach to solve this problem by creating CarDTO_ class. See http://www.hibernate.org/subprojects/jpamodelgen.html for more details. This approach is much easier. You can look at the hibernate maven plugin that implement the code generation.

If you really want to modify the existing class, then I would recommend using AspectJ with an approach similar to Spring Roo, where the aspect contains the generated code.

Edited (Example using AspectJ)

In this case, we are using AspectJ inter-type declarations that enables you to modify an existing class.

aspect CarAspect 
{
     public static final String CarDTO.VENDOR = "vendor";
     public static final String CarDTO.NAME = "name";
}

Do implement this in maven, you need

  1. a plugin to generate the CarAspect
  2. the aspectj-maven-plugin to compile (weave) the aspect

Also, Eclipse has good support for AspectJ so you can use it there too.

I have a app with a similar frontend approach to access the domain classes, but I have my domain is entirely created via a DSL implemented via Eclipse Xtext, who can be used in a maven build also. There is a sample Java domain DSL project in the xtext distribution, its easy to start from there.

This sure is not a fast "just use a maven plugin" solution but once you get into Xtext it will pay off, especially if you have a lot domain classes, or a lot similar projects.

From my domain DSL I create via code templates and a xtext generator project three classes:

  • target/generated/mydsl (generated always):
    • AbstractDomainClass (in this file i have my static string's)
  • src/main/java (generated once):
    • ConcreteDomainClass
  • src/test/java (generated once):
    • ConcreteDomainClassTest

In the abstract domain class i have all getters and setters and simple persistence stuff in it, in the concrete domain class is the more complex stuff and the test class stands for it self.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!