代码自动生成 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:

Read and parse SomeClass.java

Iterate through all fields defined in the source code

Add source code method someMethod()

Save SomeClass.java (Ideally, preserving the formatting of the existing code)

What tools and techniques are best suited to accomplish this?

EDIT

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

解决方案

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.

Updates:

mixing auto-generated code always pose a risk of someone modifying it in future to just to tweak a small behavior. It's just the matter of next build, when this changes will be lost.

you will have to solely rely on the comments on top of auto-generated source to prevent developers from doing so.

version-controlling - Lets say you update the template of someMethod(), now all of your source file's version will be updated, even if the source updates is auto-generated. you will see redundant history.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值