使用JavaPoet生成Java代码
https://github.com/square/javapoet
package cn.jyan.net.jeff;
import java.io.IOException;
import javax.lang.model.element.Modifier;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeSpec;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws IOException
{
// 定义方法
MethodSpec main = MethodSpec.methodBuilder("main")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.returns(void.class)
.addParameter(String[].class, "args")
.addStatement("$T.out.println($S)", System.class, "hello world")
.build();
// 定义属性
FieldSpec flag = FieldSpec.builder(String.class, "mFlag", Modifier.PRIVATE).build();
// 定义类
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.addField(flag)
.build();
// 定义类文件
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld).build();
// 将类文件写入指定目标
javaFile.writeTo(System.out);
}
}