以编程方式编辑/修改.java文件? (不是.class文件) [英] Editing/Modifying a .java file programmatically? (not the .class file)

查看:204
本文介绍了以编程方式编辑/修改.java文件? (不是.class文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是一段使用 CodeModel 生成java代码的代码:

So, here is a piece of code using CodeModel that generates java code:

    JCodeModel cm = new JCodeModel();
    JDefinedClass dc = cm._class("foo.Bar");
    JMethod m = dc.method(0, int.class, "foo"); 
    m.body()._return(JExpr.lit(5));
    File f = new File("C:/target/classes");
    f.mkdirs();
    cm.build(f);

此代码生成一个.java文件:

This code generates a .java file:

package foo;
public class Bar {

       int foo() {
        return  5;
    }
}

然而,我不要希望CodeModel为我创建一个新的java文件。我已经有一个.java文件,并希望在其中的方法中添加几行代码。所以,我希望API直接修改java文件/创建它的修改后的副本。有没有办法做到这一点?

However, I DO NOT want CodeModel to create a new java file for me. I do have a .java file already and would like to add a few lines of code to a method inside it. So, I would like the API to modify the java file directly/ create a modified copy of it. Is there a way to doing this?

推荐答案

我知道自原始帖子以来已经有一段时间,但其中一个更容易获得查看Java转换库似乎是 Spoon

I know it's been a while since the original post, but one of the more accessible looking Java transformation libraries appears to be Spoon.

来自 Spoon主页


Spoon使您能够转换(见下文)并分析(参见示例)
源代码。 Spoon提供了完整且细粒度的Java元模型
,其中可以访问任何程序元素(类,方法,字段,语句,
表达式......)以进行读取和修改。
Spoon作为输入源代码并生成转换后的源代码
,可以编译。

Spoon enables you to transform (see below) and analyze (see example) source code. Spoon provides a complete and fine-grained Java metamodel where any program element (classes, methods, fields, statements, expressions...) can be accessed both for reading and modification. Spoon takes as input source code and produces transformed source code ready to be compiled.

更新:Square还创建了 JavaPoet 源代码生成库,流畅的API看起来很简单,可以掌握。

Update: Square have also created the JavaPoet source-code generation library, the fluent API looks simple enough to grasp.

这篇关于以编程方式编辑/修改.java文件? (不是.class文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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