JavaPoet is a Java API for generating .java source files.
Source file generation can be useful when doing things such as annotation processing or interacting with metadata files (e.g., database schemas, protocol formats). By generating code, you eliminate the need to write boilerplate while also keeping a single source of truth for the metadata.
以上这段解释来自JavaPoet仓库中的描述。
大概意思就是JavaPoet是用来产生.java源文件的,在处理注解或者一些数据库表,协议格式等格式的元数据文件交互的时候很有用,因为你可以去除那些重复的代码,同时保证元数据代表的文件的唯一正确性。
先来看看JavaPoet能干些什么:
那我们如何使用JavaPoet库呢?
一个简单的例子
package com.example.helloworld;
public final class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, JavaPoet!");
}
}
这是一个用JavaPoet产生的简单的Java源文件。
具体实现代码如下:
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, JavaPoet!")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(main)
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
try {
//javaFile.writeTo(System.out);
javaFile.writeTo(new File("."));
} catch (IOException e) {
e.printStackTrace();
}
具体的代码例子可以参见我的仓库,直接在当前的工程目录下生成了包名路径的Java源代码文件。
具体如何更好的使用JavaPoet,请参见JavaPoet。