生成JAVA文件并在运行时使用它们 [英] Generating JAVA files and using them at runtime

查看:108
本文介绍了生成JAVA文件并在运行时使用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试Cedric Beust在其他主题中提出的以下建议。

I'm trying the following, suggested by Cedric Beust in some other thread.


您可以自己做这件事作为预测试任务:实现一个代码生成器
,以XML格式获取信息,抓取相应的Java
源文件并生成TestNG源文件,并将所有注释
放在正确的位置。然后在该文件上运行TestNG。

You could do this yourself as a pre-test task: implement a code generator that takes the information in XML form, grab the corresponding Java source file and generate a TestNG source file with all the annotations placed in the right locations. And then you run TestNG on that file.

我对代码生成一无所知。有人可以指引我正确的方向吗?一些简单的示例就很好。

I have no clue with code generation. Can someone guide me in the right direction? Some simple examples would be great.

更新:这是我要生成的内容的模板。

Update: This is the template of what I would like to generate.

public class <tobeReadFromConfigFile>
{
  @Test(groups="to be read from config file")
  public void <tobereadfromconfigfile>{
     //to be read from config file(Name of function to call)
     //to be read from config file(Name of function to call)
     //to be read from config file(Name of function to call)
  }
  .
  .
  .
}

函数内部的代码只是函数调用,必须对其进行读取和

The code inside function will be just function calls, which has to be read and copied exactly from config file.

推荐答案

FreeMarker模板如下所示:

A FreeMarker template would look something like this:

public class ${className} {
    @Test(groups="${testGroups}")
    public void ${testMethodName}() {
        <#list methods as m>
        ${m}
        </#list>   
    }
}

它将从上下文填充,本质上是一个哈希图带有 className testGroups 等条目的条目,这些条目将从XML文件中读取。 方法 Collection (如列表),也可以从XML文件中读取。

It would be filled from a context, essentially a hashmap with className, testGroups, etc. entries, that would be read from your XML file. methods would be a Collection (like a list), also read from the XML file.

当然,还有许多其他模板库。这只是一个例子。

There are many other templating libraries, of course; this is just an example.

FreeMarker

这篇关于生成JAVA文件并在运行时使用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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