JavaPoet
========
`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.
Deprecated
----------
As of 2020-10-10, Square's JavaPoet project is deprecated. We're proud of our work but we haven't
kept up on maintaining it.
If you'd like an alternative that supports the latest Java language features, one option is
[Palantir's JavaPoet](https://github.com/palantir/javapoet).
To switch to that project, you'll need new Maven coordinates:
```diff
- javapoet = { module = "com.squareup:javapoet", version = "1.13.0" }
+ javapoet = { module = "com.palantir.javapoet:javapoet", version = "0.5.0" }
```
And new imports:
```
sed -i "" \
's/com.squareup.javapoet.\([A-Za-z]*\)/com.palantir.javapoet.\1/g' \
`find . -name "*.kt" -or -name "*.java"`
```
And you might need to track some API changes where fields became functions:
```diff
- javaFile.packageName
+ javaFile.packageName()
```
### Example
Here's a (boring) `HelloWorld` class:
```java
package com.example.helloworld;
public final class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, JavaPoet!");
}
}
```
And this is the (exciting) code to generate it with 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();
javaFile.writeTo(System.out);
```
To declare the main method, we've created a `MethodSpec` "main" configured with modifiers, return
type, parameters and code statements. We add the main method to a `HelloWorld` class, and then add
that to a `HelloWorld.java` file.
In this case we write the file to `System.out`, but we could also get it as a string
(`JavaFile.toString()`) or write it to the file system (`JavaFile.writeTo()`).
The [Javadoc][javadoc] catalogs the complete JavaPoet API, which we explore below.
### Code & Control Flow
Most of JavaPoet's API uses plain old immutable Java objects. There's also builders, method chaining
and varargs to make the API friendly. JavaPoet offers models for classes & interfaces (`TypeSpec`),
fields (`FieldSpec`), methods & constructors (`MethodSpec`), parameters (`ParameterSpec`) and
annotations (`AnnotationSpec`).
But the _body_ of methods and constructors is not modeled. There's no expression class, no
statement class or syntax tree nodes. Instead, JavaPoet uses strings for code blocks:
```java
MethodSpec main = MethodSpec.methodBuilder("main")
.addCode(""
+ "int total = 0;\n"
+ "for (int i = 0; i < 10; i++) {\n"
+ " total += i;\n"
+ "}\n")
.build();
```
Which generates this:
```java
void main() {
int total = 0;
for (int i = 0; i < 10; i++) {
total += i;
}
}
```
The manual semicolons, line wrapping, and indentation are tedious and so JavaPoet offers APIs to
make it easier. There's `addStatement()` which takes care of semicolons and newline, and
`beginControlFlow()` + `endControlFlow()` which are used together for braces, newlines, and
indentation:
```java
MethodSpec main = MethodSpec.methodBuilder("main")
.addStatement("int total = 0")
.beginControlFlow("for (int i = 0; i < 10; i++)")
.addStatement("total += i")
.endControlFlow()
.build();
```
This example is lame because the generated code is constant! Suppose instead of just adding 0 to 10,
we want to make the operation and range configurable. Here's a method that generates a method:
```java
private MethodSpec computeRange(String name, int from, int to, String op) {
return MethodSpec.methodBuilder(name)
.returns(int.class)
.addStatement("int result = 1")
.beginControlFlow("for (int i = " + from + "; i < " + to + "; i++)")
.addStatement("result = result " + op + " i")
.endControlFlow()
.addStatement("return result")
.build();
}
```
And here's what we get when we call `computeRange("multiply10to20", 10, 20, "*")`:
```java
int multiply10to20() {
int result = 1;
for (int i = 10; i < 20; i++) {
result = result * i;
}
return result;
}
```
Methods generating methods! And since JavaPoet generates source instead of bytecode, you can
read through it to make sure it's right.
Some control flow statements, such as `if/else`, can have unlimited control flow possibilities.
You can handle those options using `nextControlFlow()`:
```java
MethodSpec main = MethodSpec.methodBuilder("main")
.addStatement("long now = $T.currentTimeMillis()", System.class)
.beginControlFlow("if ($T.currentTimeMillis() < now)", System.class)
.addStatement("$T.out.println($S)", System.class, "Time travelling, woo hoo!")
.nextControlFlow("else if ($T.currentTimeMillis() == now)", System.class)
.addStatement("$T.out.println($S)", System.class, "Time stood still!")
.nextControlFlow("else")
.addStatement("$T.out.println($S)", System.class, "Ok, time still moving forward")
.endControlFlow()
.build();
```
Which generates:
```java
void main() {
long now = System.currentTimeMillis();
if (System.currentTimeMillis() < now) {
System.out.println("Time travelling, woo hoo!");
} else if (System.currentTimeMillis() == now) {
System.out.println("Time stood still!");
} else {
System.out.println("Ok, time still moving forward");
}
}
```
Catching exceptions using `try/catch` is also a use case for `nextControlFlow()`:
```java
MethodSpec main = MethodSpec.methodBuilder("main")
.beginControlFlow("try")
.addStatement("throw new Exception($S)", "Failed")
.nextControlFlow("catch ($T e)", Exception.class)
.addStatement("throw new $T(e)", RuntimeException.class)
.endControlFlow()
.build();
```
Which produces:
```java
void main() {
try {
throw new Exception("Failed");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
```
### $L for Literals
The string-concatenation in calls to `beginControlFlow()` and `addStatement` is distracting. Too
many operators. To address this, JavaPoet offers a syntax inspired-by but incompatible-with
[`String.format()`][formatter]. It accepts **`$L`** to emit a **literal** value in the output. This
works just like `Formatter`'s `%s`:
```java
private MethodSpec computeRange(String name, int from, int to, String op) {
return MethodSpec.methodBuilder(name)
.returns(int.class)
.addStatement("int result = 0")
.beginControlFlow("for (int i = $L; i < $L; i++)", from, to)
.addStatement("result = result $L i", op)
.endControlFlow()
.addStatement("return result")
.build();
}
```
Literals are emitted directly to the output code with no escaping. Arguments for literals may be
strings, primitives, and a few JavaPoet types described below.
### $S for Strings
When emitting code that includes string literals, we can use **`$S`** to emit a **string**, complete
with wrapping quotation marks and escaping. Here's a program that emits 3 methods, each of which
returns its own name:
```java
public static void main(String[] args) throws Exception {
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(whatsMyName("slimShady"))
.addMethod(whatsMyName("eminem"))
.addMethod(whatsMyName("marshallMathers"))
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
没有合适的资源?快使用搜索试试~ 我知道了~
用于生成.java 源文件的 Java API .zip
共52个文件
java:39个
md:4个
txt:3个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 49 浏览量
2024-11-25
04:48:58
上传
评论
收藏 123KB ZIP 举报
温馨提示
用于生成.java 源文件的 Java API。Java诗人JavaPoet是用于生成源文件的 Java API .java。在执行注释处理或与元数据文件(例如数据库架构、协议格式)交互等操作时,源文件生成非常有用。通过生成代码,您无需编写样板文件,同时还可以为元数据保留单一可信来源。已弃用自 2020-10-10 起,Square 的 JavaPoet 项目已弃用。我们为我们的工作感到自豪,但我们没有继续维护它。如果您想要一个支持最新 Java 语言功能的替代方案,那么一个选择是 Palantir 的 JavaPoet。要切换到该项目,您需要新的 Maven 坐标- javapoet = { module = "com.squareup:javapoet", version = "1.13.0" }+ javapoet = { module = "com.palantir.javapoet:javapoet", version = "0.5.0" }新进口商品sed -i "" \ 's/com.squareup.javapoet.\([A
资源推荐
资源详情
资源评论
收起资源包目录
用于生成.java 源文件的 Java API。.zip (52个子文件)
checkstyle.xml 5KB
pom.xml 5KB
.github
CONTRIBUTING.md 722B
workflows
build.yml 515B
settings.xml 233B
标签.txt 6B
renovate.json 107B
LICENSE.txt 11KB
src
test
java
ClassNameNoPackageTest.java 1KB
com
squareup
javapoet
TestUtil.java 520B
FileReadingTest.java 5KB
TypesTest.java 1KB
AnnotationSpecTest.java 14KB
CodeBlockTest.java 12KB
JavaFileTest.java 35KB
LineWrapperTest.java 7KB
TypeNameTest.java 8KB
TypeSpecTest.java 92KB
AnnotatedTypeNameTest.java 9KB
ParameterSpecTest.java 5KB
FieldSpecTest.java 2KB
CodeWriterTest.java 644B
UtilTest.java 4KB
FileWritingTest.java 9KB
NameAllocatorTest.java 4KB
MethodSpecTest.java 17KB
TestFiler.java 3KB
AbstractTypesTest.java 11KB
TypesEclipseTest.java 5KB
ClassNameTest.java 8KB
main
java
com
squareup
javapoet
MethodSpec.java 18KB
TypeSpec.java 31KB
ArrayTypeName.java 3KB
JavaFile.java 11KB
ParameterSpec.java 6KB
CodeWriter.java 18KB
LineWrapper.java 5KB
WildcardTypeName.java 5KB
TypeName.java 15KB
AnnotationSpec.java 10KB
FieldSpec.java 5KB
ParameterizedTypeName.java 5KB
Util.java 5KB
NameAllocator.java 6KB
CodeBlock.java 16KB
TypeVariableName.java 6KB
ClassName.java 11KB
CHANGELOG.md 12KB
资源内容.txt 897B
.gitignore 150B
RELEASING.md 1KB
README.md 28KB
共 52 条
- 1
资源评论
赵闪闪168
- 粉丝: 1726
- 资源: 6172
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- NSFileManagerOperationError如何解决.md
- FileExistsError.md
- NullPointerException如何解决.md
- 激光切割机3015 ug10全套技术资料100%好用.zip
- 二叉树的深度计算方法PDF
- BAT加密解密程序单纯的批处理代码
- Java+Swing+Mysql实现电影院票务管理系统(高分项目)
- 矿泉水瓶瓶装液体膜包机step全套技术资料100%好用.zip
- MemoryLeakError解决办法.md
- IndexOutOfBoundsException如何解决.md
- ReadOnlyBufferException(解决方案).md
- Python编程全面介绍:从基础知识到实用技巧
- Java+Swing+Mysql实现的图书借阅管理系统(98分大作业)
- 超市企业文化培训手册.ppt
- 陈德起:创建学习型组织.ppt
- 皓志集团《企业文化手册》.ppt
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功