简体   繁体   English

生成的带有反射的Java源代码

[英]Generated Java source with reflection

In my Java application I have a class Foo 在我的Java应用程序中,我有一个Foo类

class Foo {
  String field1;
  String field2;
}

I would like to have some generated code which uses reflection on the fields in this class (Imaginary template language) 我想要一些生成的代码,该代码在此类的字段上使用反射(虚构模板语言)

#for each Field $f in Foo.class.getDeclaredFields()
  #writeFile $f.java
    public @interface $f {
    }

The end goal is to have Field1.java and Field2.java with just a simple @interface definition inside each. 最终目标是使Field1.java和Field2.java各自内部仅具有一个简单的@interface定义。

Is there a templating language available which could do this generation as part of a Maven build process? 是否有可用的模板语言作为Maven构建过程的一部分来进行这一代?

The closest I have been able to find is JET , but this project seems more geared towards generating Java source to be available at runtime, not at compile time. 我能找到的最接近的是JET ,但是这个项目似乎更适合于生成Java源代码,使其在运行时可用,而不是在编译时可用。 In theory I could probably make this work using AntRun along with several Javac and Java tasks, but it would be cumbersome. 从理论上讲,我可以使用AntRun以及几个Javac和Java任务来完成这项工作,但这会很麻烦。

The actual use case which I need this for is generating BindingAnnotations for Google Guice (which will be used in GWT source, so they must exist as .java files at compile time). 我需要的实际用例是为Google Guice生成BindingAnnotations (将在GWT源代码中使用,因此在编译时它们必须作为.java文件存在)。

Take a look at Acceleo it is based on XSL Templates to generate source code . 看一下Acceleo,它基于XSL模板生成源代码。 I used it with EMF to generate source code from a Data Model designed by the user. 我将它与EMF一起使用,以从用户设计的数据模型生成源代码。

I would suggest two options here: 我在这里建议两个选择:

  1. Apache Velocity: it provides a template language looking close to what you describe. Apache Velocity:它提供了一种模板语言,看起来与您所描述的非常接近。 Look into it here . 在这里看看。 You could probably be interested by their engine. 您可能会对他们的引擎感兴趣。

  2. GWTP seems to do something similar to what you are wanting to do. GWTP似乎在执行与您要执行的操作类似的操作。 It looks likes they are using annotation processor to perform their code generation. 看起来他们正在使用注释处理器执行代码生成。 Here is a processor example and their project home is here . 这是一个处理器示例 ,他们的项目主页在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM