自动生成Java源代码 [英] Automatically generating Java source code

查看:135
本文介绍了自动生成Java源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种基于类中定义的字段自动为现有Java源代码文件中的新方法生成源代码的方法。

I'm looking for a way to automatically generate source code for new methods within an existing Java source code file, based on the fields defined within the class.

本质上,我希望执行以下步骤:

In essence, I'm looking to execute the following steps:


  1. 读取并解析 SomeClass.java

  2. 遍历源代码中定义的所有字段

  3. 添加源代码方法 someMethod()

  4. 保存 SomeClass.java (理想情况下,保留现有代码的格式)

  1. Read and parse SomeClass.java
  2. Iterate through all fields defined in the source code
  3. Add source code method someMethod()
  4. Save SomeClass.java (Ideally, preserving the formatting of the existing code)

什么工具和技术最适合完成此任务?

What tools and techniques are best suited to accomplish this?

编辑 >

我不想在运行时生成代码;我想扩充现有的Java 源代码

I don't want to generate code at runtime; I want to augment existing Java source code

推荐答案

使用自动生成的方法修改相同的Java源文件代码是维护的噩梦。考虑生成一个新类,以扩展您当前的类并添加所需的方法。使用反射从用户定义的类读取并为自动生成的类创建速度模板。然后为每个用户定义的类生成其扩展类。将代码生成阶段集成到构建生命周期中。

Modifying the same java source file with auto-generated code is maintenance nightmare. Consider generating a new class that extends you current class and adds the desired method. Use reflection to read from user-defined class and create velocity templates for the auto-generating classes. Then for each user-defined class generate its extending class. Integrate the code generation phase in your build lifecycle.

或者您可以使用字节码增强技术来增强类,而无需修改源代码。

Or you may use 'bytecode enhancement' techniques to enhance the classes without having to modify the source code.

更新:


  1. 混合自动生成的代码始终会带来将来有人对其进行修改的风险只是为了调整一个小行为。

  2. 您将仅依赖于自动生成的源代码之上的注释来防止开发人员这样做。 / li>
  3. 版本控制-假设您更新了someMethod()的模板,现在即使源更新是自动生成的,您的所有源文件的版本也会被更新。您将看到多余的历史记录。

这篇关于自动生成Java源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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