This repository has been archived by the owner on Apr 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathREADME.html
505 lines (466 loc) · 46.2 KB
/
README.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<h1 id="javapoet">JavaPoet</h1>
<p><code>JavaPoet</code> is a Java API for generating <code>.java</code> source files.</p>
<p>Source file generation can 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.</p>
<h3 id="example">Example</h3>
<p>Here's a (boring) <code>HelloWorld</code> class:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">package com.example.helloworld;</span>
<span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> HelloWorld {
<span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
System.<span class="fu">out</span>.<span class="fu">println</span>(<span class="st">"Hello, JavaPoet!"</span>);
}
}</code></pre>
<p>And this is the (exciting) code to generate it with JavaPoet:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec main = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"main"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">STATIC</span>)
.<span class="fu">returns</span>(<span class="dt">void</span>.<span class="fu">class</span>)
.<span class="fu">addParameter</span>(String[].<span class="fu">class</span>, <span class="st">"args"</span>)
.<span class="fu">addStatement</span>(<span class="st">"$T.out.println($S)"</span>, System.<span class="fu">class</span>, <span class="st">"Hello, JavaPoet!"</span>)
.<span class="fu">build</span>();
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">addMethod</span>(main)
.<span class="fu">build</span>();
JavaFile javaFile = JavaFile.<span class="fu">builder</span>(<span class="st">"com.example.helloworld"</span>, helloWorld)
.<span class="fu">build</span>();
javaFile.<span class="fu">writeTo</span>(System.<span class="fu">out</span>);</code></pre>
<p>To declare the main method, we've created a <code>MethodSpec</code> "main" configured with modifiers, return type, parameters and code statements. We add the main method to a <code>HelloWorld</code> class, and then add that to a <code>HelloWorld.java</code> file.</p>
<p>In this case we write the file to <code>System.out</code>, but we could also get it as a string (<code>JavaFile.toString()</code>) or write it to the file system (<code>JavaPoet.writeTo()</code>).</p>
<p>The <a href="https://square.github.io/javapoet/javadoc/javapoet/">Javadoc</a> catalogs the complete JavaPoet API, which we explore below.</p>
<h3 id="code-control-flow">Code & Control Flow</h3>
<p>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 (<code>TypeSpec</code>), fields (<code>FieldSpec</code>), methods & constructors (<code>MethodSpec</code>), parameters (<code>ParameterSpec</code>) and annotations (<code>AnnotationSpec</code>).</p>
<p>But the <em>body</em> 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:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec main = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"main"</span>)
.<span class="fu">addCode</span>(<span class="st">""</span>
+ <span class="st">"int total = 0;</span><span class="ch">\n</span><span class="st">"</span>
+ <span class="st">"for (int i = 0; i < 10; i++) {</span><span class="ch">\n</span><span class="st">"</span>
+ <span class="st">" total += i;</span><span class="ch">\n</span><span class="st">"</span>
+ <span class="st">"}</span><span class="ch">\n</span><span class="st">"</span>)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="dt">void</span> <span class="fu">main</span>() {
<span class="dt">int</span> total = <span class="dv">0</span>;
<span class="kw">for</span> (<span class="dt">int</span> i = <span class="dv">0</span>; i < <span class="dv">10</span>; i++) {
total += i;
}
}</code></pre>
<p>The manual semicolons, line wrapping, and indentation are tedious and so JavaPoet offers APIs to make it easier. There's <code>addStatement()</code> which takes care of semicolons and newline, and <code>beginControlFlow()</code> + <code>endControlFlow()</code> which are used together for braces, newlines, and indentation:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec main = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"main"</span>)
.<span class="fu">addStatement</span>(<span class="st">"int total = 0"</span>)
.<span class="fu">beginControlFlow</span>(<span class="st">"for (int i = 0; i < 10; i++)"</span>)
.<span class="fu">addStatement</span>(<span class="st">"total += i"</span>)
.<span class="fu">endControlFlow</span>()
.<span class="fu">build</span>();</code></pre>
<p>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:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">private</span> MethodSpec <span class="fu">computeRange</span>(String name, <span class="dt">int</span> from, <span class="dt">int</span> to, String op) {
<span class="kw">return</span> MethodSpec.<span class="fu">methodBuilder</span>(name)
.<span class="fu">returns</span>(<span class="dt">int</span>.<span class="fu">class</span>)
.<span class="fu">addStatement</span>(<span class="st">"int result = 0"</span>)
.<span class="fu">beginControlFlow</span>(<span class="st">"for (int i = "</span> + from + <span class="st">"; i < "</span> + to + <span class="st">"; i++)"</span>)
.<span class="fu">addStatement</span>(<span class="st">"result = result "</span> + op + <span class="st">" i"</span>)
.<span class="fu">endControlFlow</span>()
.<span class="fu">addStatement</span>(<span class="st">"return result"</span>)
.<span class="fu">build</span>();
}</code></pre>
<p>And here's what we get when we call <code>computeRange("multiply10to20", 10, 20, "*")</code>:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="dt">int</span> <span class="fu">multiply10to20</span>() {
<span class="dt">int</span> result = <span class="dv">0</span>;
<span class="kw">for</span> (<span class="dt">int</span> i = <span class="dv">10</span>; i < <span class="dv">20</span>; i++) {
result = result * i;
}
<span class="kw">return</span> result;
}</code></pre>
<p>Methods generating methods! And since JavaPoet generates source instead of bytecode, you can read through it to make sure it's right.</p>
<h3 id="l-for-literals">$L for Literals</h3>
<p>The string-concatenation in calls to <code>beginControlFlow()</code> and <code>addStatement</code> is distracting. Too many operators. To address this, JavaPoet offers a syntax inspired-by but incompatible-with <a href="http://developer.android.com/reference/java/util/Formatter.html"><code>String.format()</code></a>. It accepts <strong><code>$L</code></strong> to emit a <strong>literal</strong> value in the output. This works just like <code>Formatter</code>'s <code>%s</code>:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">private</span> MethodSpec <span class="fu">computeRange</span>(String name, <span class="dt">int</span> from, <span class="dt">int</span> to, String op) {
<span class="kw">return</span> MethodSpec.<span class="fu">methodBuilder</span>(name)
.<span class="fu">returns</span>(<span class="dt">int</span>.<span class="fu">class</span>)
.<span class="fu">addStatement</span>(<span class="st">"int result = 0"</span>)
.<span class="fu">beginControlFlow</span>(<span class="st">"for (int i = $L; i < $L; i++)"</span>, from, to)
.<span class="fu">addStatement</span>(<span class="st">"result = result $L i"</span>, op)
.<span class="fu">endControlFlow</span>()
.<span class="fu">addStatement</span>(<span class="st">"return result"</span>)
.<span class="fu">build</span>();
}</code></pre>
<p>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.</p>
<h3 id="s-for-strings">$S for Strings</h3>
<p>When emitting code that includes string literals, we can use <strong><code>$S</code></strong> to emit a <strong>string</strong>, complete with wrapping quotation marks and escaping. Here's a program that emits 3 methods, each of which returns its own name:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) <span class="kw">throws</span> Exception {
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">addMethod</span>(<span class="fu">whatsMyName</span>(<span class="st">"slimShady"</span>))
.<span class="fu">addMethod</span>(<span class="fu">whatsMyName</span>(<span class="st">"eminem"</span>))
.<span class="fu">addMethod</span>(<span class="fu">whatsMyName</span>(<span class="st">"marshallMathers"</span>))
.<span class="fu">build</span>();
JavaFile javaFile = JavaFile.<span class="fu">builder</span>(<span class="st">"com.example.helloworld"</span>, helloWorld)
.<span class="fu">build</span>();
javaFile.<span class="fu">writeTo</span>(System.<span class="fu">out</span>);
}
<span class="kw">private</span> <span class="dt">static</span> MethodSpec <span class="fu">whatsMyName</span>(String name) {
<span class="kw">return</span> MethodSpec.<span class="fu">methodBuilder</span>(name)
.<span class="fu">returns</span>(String.<span class="fu">class</span>)
.<span class="fu">addStatement</span>(<span class="st">"return $S"</span>, name)
.<span class="fu">build</span>();
}</code></pre>
<p>In this case, using <code>$S</code> gives us quotation marks:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> HelloWorld {
String <span class="fu">slimShady</span>() {
<span class="kw">return</span> <span class="st">"slimShady"</span>;
}
String <span class="fu">eminem</span>() {
<span class="kw">return</span> <span class="st">"eminem"</span>;
}
String <span class="fu">marshallMathers</span>() {
<span class="kw">return</span> <span class="st">"marshallMathers"</span>;
}
}</code></pre>
<h3 id="t-for-types">$T for Types</h3>
<p>We Java programmers love our types: they make our code easier to understand. And JavaPoet is on board. It has rich built-in support for types, including automatic generation of <code>import</code> statements. Just use <strong><code>$T</code></strong> to reference <strong>types</strong>:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec today = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"today"</span>)
.<span class="fu">returns</span>(Date.<span class="fu">class</span>)
.<span class="fu">addStatement</span>(<span class="st">"return new $T()"</span>, Date.<span class="fu">class</span>)
.<span class="fu">build</span>();
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">addMethod</span>(today)
.<span class="fu">build</span>();
JavaFile javaFile = JavaFile.<span class="fu">builder</span>(<span class="st">"com.example.helloworld"</span>, helloWorld)
.<span class="fu">build</span>();
javaFile.<span class="fu">writeTo</span>(System.<span class="fu">out</span>);</code></pre>
<p>That generates the following <code>.java</code> file, complete with the necessary <code>import</code>:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">package com.example.helloworld;</span>
<span class="kw">import java.util.Date;</span>
<span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> HelloWorld {
Date <span class="fu">today</span>() {
<span class="kw">return</span> <span class="kw">new</span> Date();
}
}</code></pre>
<p>We passed <code>Date.class</code> to reference a class that just-so-happens to be available when we're generating code. This doesn't need to be the case. Here's a similar example, but this one references a class that doesn't exist (yet):</p>
<pre class="sourceCode java"><code class="sourceCode java">ClassName hoverboard = ClassName.<span class="fu">get</span>(<span class="st">"com.mattel"</span>, <span class="st">"Hoverboard"</span>);
MethodSpec today = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"tomorrow"</span>)
.<span class="fu">returns</span>(hoverboard)
.<span class="fu">addStatement</span>(<span class="st">"return new $T()"</span>, hoverboard)
.<span class="fu">build</span>();</code></pre>
<p>And that not-yet-existent class is imported as well:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">package com.example.helloworld;</span>
<span class="kw">import com.mattel.Hoverboard;</span>
<span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> HelloWorld {
Hoverboard <span class="fu">tomorrow</span>() {
<span class="kw">return</span> <span class="kw">new</span> <span class="fu">Hoverboard</span>();
}
}</code></pre>
<p>The <code>ClassName</code> type is very important, and you'll need it frequently when you're using JavaPoet. It can identify any <em>declared</em> class. Declared types are just the beginning of Java's rich type system: we also have arrays, parameterized types, wildcard types, and type variables. JavaPoet has classes for building each of these:</p>
<pre class="sourceCode java"><code class="sourceCode java">ClassName hoverboard = ClassName.<span class="fu">get</span>(<span class="st">"com.mattel"</span>, <span class="st">"Hoverboard"</span>);
ClassName list = ClassName.<span class="fu">get</span>(<span class="st">"java.util"</span>, <span class="st">"List"</span>);
ClassName arrayList = ClassName.<span class="fu">get</span>(<span class="st">"java.util"</span>, <span class="st">"ArrayList"</span>);
TypeName listOfHoverboards = ParameterizedTypeName.<span class="fu">get</span>(list, hoverboard);
MethodSpec today = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"beyond"</span>)
.<span class="fu">returns</span>(listOfHoverboards)
.<span class="fu">addStatement</span>(<span class="st">"$T result = new $T<>()"</span>, listOfHoverboards, arrayList)
.<span class="fu">addStatement</span>(<span class="st">"result.add(new $T())"</span>, hoverboard)
.<span class="fu">addStatement</span>(<span class="st">"result.add(new $T())"</span>, hoverboard)
.<span class="fu">addStatement</span>(<span class="st">"result.add(new $T())"</span>, hoverboard)
.<span class="fu">addStatement</span>(<span class="st">"return result"</span>)
.<span class="fu">build</span>();</code></pre>
<p>JavaPoet will decompose each type and import its components where possible.</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">package com.example.helloworld;</span>
<span class="kw">import com.mattel.Hoverboard;</span>
<span class="kw">import java.util.ArrayList;</span>
<span class="kw">import java.util.List;</span>
<span class="kw">public</span> <span class="dt">final</span> <span class="kw">class</span> HelloWorld {
List<Hoverboard> <span class="fu">beyond</span>() {
List<Hoverboard> result = <span class="kw">new</span> ArrayList<>();
result.<span class="fu">add</span>(<span class="kw">new</span> <span class="fu">Hoverboard</span>());
result.<span class="fu">add</span>(<span class="kw">new</span> <span class="fu">Hoverboard</span>());
result.<span class="fu">add</span>(<span class="kw">new</span> <span class="fu">Hoverboard</span>());
<span class="kw">return</span> result;
}
}</code></pre>
<h3 id="n-for-names">$N for Names</h3>
<p>Generated code is often self-referential. Use <strong><code>$N</code></strong> to refer to another generated declaration by its name. Here's a method that calls another:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> String <span class="fu">byteToHex</span>(<span class="dt">int</span> b) {
<span class="dt">char</span>[] result = <span class="kw">new</span> <span class="dt">char</span>[<span class="dv">2</span>];
result[<span class="dv">0</span>] = <span class="fu">hexDigit</span>((b >>> <span class="dv">4</span>) & <span class="bn">0xf</span>);
result[<span class="dv">1</span>] = <span class="fu">hexDigit</span>(b & <span class="bn">0xf</span>);
<span class="kw">return</span> <span class="kw">new</span> String(result);
}
<span class="kw">public</span> <span class="dt">char</span> <span class="fu">hexDigit</span>(<span class="dt">int</span> i) {
<span class="kw">return</span> (<span class="dt">char</span>) (i < <span class="dv">10</span> ? i + '<span class="dv">0</span>' : i - <span class="dv">10</span> + 'a');
}</code></pre>
<p>When generating the code above, we pass the <code>hexDigit()</code> method as an argument to the <code>byteToHex()</code> method using <code>$N</code>:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec hexDigit = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"hexDigit"</span>)
.<span class="fu">addParameter</span>(<span class="dt">int</span>.<span class="fu">class</span>, <span class="st">"i"</span>)
.<span class="fu">returns</span>(<span class="dt">char</span>.<span class="fu">class</span>)
.<span class="fu">addStatement</span>(<span class="st">"return (char) (i < 10 ? i + '0' : i - 10 + 'a')"</span>)
.<span class="fu">build</span>();
MethodSpec byteToHex = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"byteToHex"</span>)
.<span class="fu">addParameter</span>(<span class="dt">int</span>.<span class="fu">class</span>, <span class="st">"b"</span>)
.<span class="fu">returns</span>(String.<span class="fu">class</span>)
.<span class="fu">addStatement</span>(<span class="st">"char[] result = new char[2]"</span>)
.<span class="fu">addStatement</span>(<span class="st">"result[0] = $N((b >>> 4) & 0xf)"</span>, hexDigit)
.<span class="fu">addStatement</span>(<span class="st">"result[1] = $N(b & 0xf)"</span>, hexDigit)
.<span class="fu">addStatement</span>(<span class="st">"return new String(result)"</span>)
.<span class="fu">build</span>();</code></pre>
<h3 id="methods">Methods</h3>
<p>All of the above methods have a code body. Use <code>Modifiers.ABSTRACT</code> to get a method without any body. This is only legal if the enclosing class is either abstract or an interface.</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec flux = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"flux"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">ABSTRACT</span>, Modifier.<span class="fu">PROTECTED</span>)
.<span class="fu">build</span>();
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">ABSTRACT</span>)
.<span class="fu">addMethod</span>(flux)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">abstract</span> <span class="kw">class</span> HelloWorld {
<span class="kw">protected</span> <span class="kw">abstract</span> <span class="dt">void</span> <span class="fu">flux</span>();
}</code></pre>
<p>The other modifiers work where permitted. Note that when specifying modifiers, JavaPoet uses <a href="http://docs.oracle.com/javase/8/docs/api/javax/lang/model/element/Modifier.html"><code>javax.lang.model.element.Modifier</code></a>, a class that is not available on Android. This limitation applies to code-generating-code only; the output code runs everywhere: JVMs, Android, and GWT.</p>
<p>Methods also have parameters, exceptions, varargs, Javadoc, annotations, type variables, and a return type. All of these are configured with <code>MethodSpec.Builder</code>.</p>
<h3 id="constructors">Constructors</h3>
<p><code>MethodSpec</code> is a slight misnomer; it can also be used for constructors:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec flux = MethodSpec.<span class="fu">constructorBuilder</span>()
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addParameter</span>(String.<span class="fu">class</span>, <span class="st">"greeting"</span>)
.<span class="fu">addStatement</span>(<span class="st">"this.$N = $N"</span>, <span class="st">"greeting"</span>, <span class="st">"greeting"</span>)
.<span class="fu">build</span>();
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addField</span>(String.<span class="fu">class</span>, <span class="st">"greeting"</span>, Modifier.<span class="fu">PRIVATE</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">addMethod</span>(flux)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> HelloWorld {
<span class="kw">private</span> <span class="dt">final</span> String greeting;
<span class="kw">public</span> <span class="fu">HelloWorld</span>(String greeting) {
<span class="kw">this</span>.<span class="fu">greeting</span> = greeting;
}
}</code></pre>
<p>For the most part, constructors work just like methods. When emitting code, JavaPoet will place constructors before methods in the output file.</p>
<h3 id="parameters">Parameters</h3>
<p>Declare parameters on methods and constructors with either <code>ParameterSpec.builder()</code> or <code>MethodSpec</code>'s convenient <code>addParameter()</code> API:</p>
<pre class="sourceCode java"><code class="sourceCode java">ParameterSpec android = ParameterSpec.<span class="fu">builder</span>(String.<span class="fu">class</span>, <span class="st">"android"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">FINAL</span>)
.<span class="fu">build</span>();
MethodSpec welcomeOverlords = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"welcomeOverlords"</span>)
.<span class="fu">addParameter</span>(android)
.<span class="fu">addParameter</span>(String.<span class="fu">class</span>, <span class="st">"robot"</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">build</span>();</code></pre>
<p>Though the code above to generate <code>android</code> and <code>robot</code> parameters is different, the output is the same:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="dt">void</span> <span class="fu">welcomeOverlords</span>(<span class="dt">final</span> String android, <span class="dt">final</span> String robot) {
}</code></pre>
<p>The extended <code>Builder</code> form is necessary when the parameter has annotations (such as <code>@Nullable</code>).</p>
<h3 id="fields">Fields</h3>
<p>Like parameters, fields can be created either with builders or by using convenient helper methods:</p>
<pre class="sourceCode java"><code class="sourceCode java">FieldSpec android = FieldSpec.<span class="fu">builder</span>(String.<span class="fu">class</span>, <span class="st">"android"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PRIVATE</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">build</span>();
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addField</span>(android)
.<span class="fu">addField</span>(String.<span class="fu">class</span>, <span class="st">"robot"</span>, Modifier.<span class="fu">PRIVATE</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">build</span>();</code></pre>
<p>Which generates:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> HelloWorld {
<span class="kw">private</span> <span class="dt">final</span> String android;
<span class="kw">private</span> <span class="dt">final</span> String robot;
}</code></pre>
<p>The extended <code>Builder</code> form is necessary when a field has Javadoc, annotations, or a field initializer. Field initializers use the same <a href="http://developer.android.com/reference/java/util/Formatter.html"><code>String.format()</code></a>-like syntax as the code blocks above:</p>
<pre class="sourceCode java"><code class="sourceCode java">FieldSpec android = FieldSpec.<span class="fu">builder</span>(String.<span class="fu">class</span>, <span class="st">"android"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PRIVATE</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">initializer</span>(<span class="st">"$S + $L"</span>, <span class="st">"Lollipop v."</span>, <span class="fl">5.</span>0d)
.<span class="fu">build</span>();</code></pre>
<p>Which generates:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">private</span> <span class="dt">final</span> String android = <span class="st">"Lollipop v."</span> + <span class="fl">5.0</span>;</code></pre>
<h3 id="interfaces">Interfaces</h3>
<p>JavaPoet has no trouble with interfaces. Note that interface methods must always be <code>PUBLIC ABSTRACT</code> and interface fields must always be <code>PUBLIC STATIC FINAL</code>. These modifiers are necessary when defining the interface:</p>
<pre class="sourceCode java"><code class="sourceCode java">TypeSpec helloWorld = TypeSpec.<span class="fu">interfaceBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addField</span>(FieldSpec.<span class="fu">builder</span>(String.<span class="fu">class</span>, <span class="st">"ONLY_THING_THAT_IS_CONSTANT"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">STATIC</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">initializer</span>(<span class="st">"$S"</span>, <span class="st">"change"</span>)
.<span class="fu">build</span>())
.<span class="fu">addMethod</span>(MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"beep"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">ABSTRACT</span>)
.<span class="fu">build</span>())
.<span class="fu">build</span>();</code></pre>
<p>But these modifiers are omitted when the code is generated. These are the defaults so we don't need to include them for <code>javac</code>'s benefit!</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">interface</span> HelloWorld {
String ONLY_THING_THAT_IS_CONSTANT = <span class="st">"change"</span>;
<span class="dt">void</span> <span class="fu">beep</span>();
}</code></pre>
<h3 id="enums">Enums</h3>
<p>Use <code>enumBuilder</code> to create the enum type, and <code>addEnumConstant()</code> for each value:</p>
<pre class="sourceCode java"><code class="sourceCode java">TypeSpec helloWorld = TypeSpec.<span class="fu">enumBuilder</span>(<span class="st">"Roshambo"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addEnumConstant</span>(<span class="st">"ROCK"</span>)
.<span class="fu">addEnumConstant</span>(<span class="st">"SCISSORS"</span>)
.<span class="fu">addEnumConstant</span>(<span class="st">"PAPER"</span>)
.<span class="fu">build</span>();</code></pre>
<p>To generate this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">enum</span> Roshambo {
ROCK,
SCISSORS,
PAPER
}</code></pre>
<p>Fancy enums are supported, where the enum values override methods or call a superclass constructor. Here's a comprehensive example:</p>
<pre class="sourceCode java"><code class="sourceCode java">TypeSpec helloWorld = TypeSpec.<span class="fu">enumBuilder</span>(<span class="st">"Roshambo"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addEnumConstant</span>(<span class="st">"ROCK"</span>, TypeSpec.<span class="fu">anonymousClassBuilder</span>(<span class="st">"$S"</span>, <span class="st">"fist"</span>)
.<span class="fu">addMethod</span>(MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"toString"</span>)
.<span class="fu">addAnnotation</span>(Override.<span class="fu">class</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addStatement</span>(<span class="st">"return $S"</span>, <span class="st">"avalanche!"</span>)
.<span class="fu">build</span>())
.<span class="fu">build</span>())
.<span class="fu">addEnumConstant</span>(<span class="st">"SCISSORS"</span>, TypeSpec.<span class="fu">anonymousClassBuilder</span>(<span class="st">"$S"</span>, <span class="st">"peace"</span>)
.<span class="fu">build</span>())
.<span class="fu">addEnumConstant</span>(<span class="st">"PAPER"</span>, TypeSpec.<span class="fu">anonymousClassBuilder</span>(<span class="st">"$S"</span>, <span class="st">"flat"</span>)
.<span class="fu">build</span>())
.<span class="fu">addField</span>(String.<span class="fu">class</span>, <span class="st">"handsign"</span>, Modifier.<span class="fu">PRIVATE</span>, Modifier.<span class="fu">FINAL</span>)
.<span class="fu">addMethod</span>(MethodSpec.<span class="fu">constructorBuilder</span>()
.<span class="fu">addParameter</span>(String.<span class="fu">class</span>, <span class="st">"handsign"</span>)
.<span class="fu">addStatement</span>(<span class="st">"this.$N = $N"</span>, <span class="st">"handsign"</span>, <span class="st">"handsign"</span>)
.<span class="fu">build</span>())
.<span class="fu">build</span>();</code></pre>
<p>Which generates this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">enum</span> Roshambo {
<span class="fu">ROCK</span>(<span class="st">"fist"</span>) {
<span class="fu">@Override</span>
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">toString</span>() {
<span class="kw">return</span> <span class="st">"avalanche!"</span>;
}
},
<span class="fu">SCISSORS</span>(<span class="st">"peace"</span>),
<span class="fu">PAPER</span>(<span class="st">"flat"</span>);
<span class="kw">private</span> <span class="dt">final</span> String handsign;
<span class="fu">Roshambo</span>(String handsign) {
<span class="kw">this</span>.<span class="fu">handsign</span> = handsign;
}
}</code></pre>
<h3 id="anonymous-inner-classes">Anonymous Inner Classes</h3>
<p>In the enum code, we used <code>Types.anonymousInnerClass()</code>. Anonymous inner classes can also be used in code blocks. They are values that can be referenced with <code>$L</code>:</p>
<pre class="sourceCode java"><code class="sourceCode java">TypeSpec comparator = TypeSpec.<span class="fu">anonymousClassBuilder</span>(<span class="st">""</span>)
.<span class="fu">addSuperinterface</span>(ParameterizedTypeName.<span class="fu">get</span>(Comparator.<span class="fu">class</span>, String.<span class="fu">class</span>))
.<span class="fu">addMethod</span>(MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"compare"</span>)
.<span class="fu">addAnnotation</span>(Override.<span class="fu">class</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addParameter</span>(String.<span class="fu">class</span>, <span class="st">"a"</span>)
.<span class="fu">addParameter</span>(String.<span class="fu">class</span>, <span class="st">"b"</span>)
.<span class="fu">addStatement</span>(<span class="st">"return $N.length() - $N.length()"</span>, <span class="st">"a"</span>, <span class="st">"b"</span>)
.<span class="fu">build</span>())
.<span class="fu">build</span>();
TypeSpec helloWorld = TypeSpec.<span class="fu">classBuilder</span>(<span class="st">"HelloWorld"</span>)
.<span class="fu">addMethod</span>(MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"sortByLength"</span>)
.<span class="fu">addParameter</span>(ParameterizedTypeName.<span class="fu">get</span>(List.<span class="fu">class</span>, String.<span class="fu">class</span>), <span class="st">"strings"</span>)
.<span class="fu">addStatement</span>(<span class="st">"$T.sort($N, $L)"</span>, Collections.<span class="fu">class</span>, <span class="st">"strings"</span>, comparator)
.<span class="fu">build</span>())
.<span class="fu">build</span>();</code></pre>
<p>This generates a method that contains a class that contains a method:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="dt">void</span> <span class="fu">sortByLength</span>(List<String> strings) {
Collections.<span class="fu">sort</span>(strings, <span class="kw">new</span> Comparator<String>() {
<span class="fu">@Override</span>
<span class="kw">public</span> <span class="dt">void</span> <span class="fu">compare</span>(String a, String b) {
<span class="kw">return</span> a.<span class="fu">length</span>() - b.<span class="fu">length</span>();
}
});
}</code></pre>
<p>One particularly tricky part of defining anonymous inner classes is the arguments to the superclass constructor. In the above code we're passing the empty string for no arguments: <code>TypeSpec.anonymousClassBuilder("")</code>. To pass different parameters use JavaPoet's code block syntax with commas to separate arguments.</p>
<h3 id="annotations">Annotations</h3>
<p>Simple annotations are easy:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec toString = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"toString"</span>)
.<span class="fu">addAnnotation</span>(Override.<span class="fu">class</span>)
.<span class="fu">returns</span>(String.<span class="fu">class</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>)
.<span class="fu">addStatement</span>(<span class="st">"return $S"</span>, <span class="st">"Hoverboard"</span>)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this method with an <code>@Override</code> annotation:</p>
<pre class="sourceCode java"><code class="sourceCode java"> <span class="fu">@Override</span>
<span class="kw">public</span> String <span class="fu">toString</span>() {
<span class="kw">return</span> <span class="st">"Hoverboard"</span>;
}</code></pre>
<p>Use <code>AnnotationSpec.builder()</code> to set properties on annotations:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec logRecord = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"recordEvent"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">ABSTRACT</span>)
.<span class="fu">addAnnotation</span>(AnnotationSpec.<span class="fu">builder</span>(Headers.<span class="fu">class</span>)
.<span class="fu">addMember</span>(<span class="st">"accept"</span>, <span class="st">"$S"</span>, <span class="st">"application/json; charset=utf-8"</span>)
.<span class="fu">addMember</span>(<span class="st">"userAgent"</span>, <span class="st">"$S"</span>, <span class="st">"Square Cash"</span>)
.<span class="fu">build</span>())
.<span class="fu">addParameter</span>(LogRecord.<span class="fu">class</span>, <span class="st">"logRecord"</span>)
.<span class="fu">returns</span>(LogReceipt.<span class="fu">class</span>)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this annotation with <code>accept</code> and <code>userAgent</code> properties:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="fu">@Headers</span>(
accept = <span class="st">"application/json; charset=utf-8"</span>,
userAgent = <span class="st">"Square Cash"</span>
)
LogReceipt <span class="fu">recordEvent</span>(LogRecord logRecord);</code></pre>
<p>When you get fancy, annotation values can be annotations themselves. Use <code>$L</code> for embedded annotations:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec logRecord = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"recordEvent"</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">ABSTRACT</span>)
.<span class="fu">addAnnotation</span>(AnnotationSpec.<span class="fu">builder</span>(HeaderList.<span class="fu">class</span>)
.<span class="fu">addMember</span>(<span class="st">"value"</span>, <span class="st">"$L"</span>, AnnotationSpec.<span class="fu">builder</span>(Header.<span class="fu">class</span>)
.<span class="fu">addMember</span>(<span class="st">"name"</span>, <span class="st">"$S"</span>, <span class="st">"Accept"</span>)
.<span class="fu">addMember</span>(<span class="st">"value"</span>, <span class="st">"$S"</span>, <span class="st">"application/json; charset=utf-8"</span>)
.<span class="fu">build</span>())
.<span class="fu">addMember</span>(<span class="st">"value"</span>, <span class="st">"$L"</span>, AnnotationSpec.<span class="fu">builder</span>(Header.<span class="fu">class</span>)
.<span class="fu">addMember</span>(<span class="st">"name"</span>, <span class="st">"$S"</span>, <span class="st">"User-Agent"</span>)
.<span class="fu">addMember</span>(<span class="st">"value"</span>, <span class="st">"$S"</span>, <span class="st">"Square Cash"</span>)
.<span class="fu">build</span>())
.<span class="fu">build</span>())
.<span class="fu">addParameter</span>(LogRecord.<span class="fu">class</span>, <span class="st">"logRecord"</span>)
.<span class="fu">returns</span>(LogReceipt.<span class="fu">class</span>)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="fu">@HeaderList</span>({
<span class="fu">@Header</span>(name = <span class="st">"Accept"</span>, value = <span class="st">"application/json; charset=utf-8"</span>),
<span class="fu">@Header</span>(name = <span class="st">"User-Agent"</span>, value = <span class="st">"Square Cash"</span>)
})
LogReceipt <span class="fu">recordEvent</span>(LogRecord logRecord);</code></pre>
<p>Note that you can call <code>addMember()</code> multiple times with the same property name to populate a list of values for that property.</p>
<h3 id="javadoc">Javadoc</h3>
<p>Fields, methods and types can be documented with Javadoc:</p>
<pre class="sourceCode java"><code class="sourceCode java">MethodSpec dismiss = MethodSpec.<span class="fu">methodBuilder</span>(<span class="st">"dismiss"</span>)
.<span class="fu">addJavadoc</span>(<span class="st">"Hides {@code message} from the caller's history. Other</span><span class="ch">\n</span><span class="st">"</span>
+ <span class="st">"participants in the conversation will continue to see the</span><span class="ch">\n</span><span class="st">"</span>
+ <span class="st">"message in their own history unless they also delete it.</span><span class="ch">\n</span><span class="st">"</span>)
.<span class="fu">addJavadoc</span>(<span class="st">"</span><span class="ch">\n</span><span class="st">"</span>)
.<span class="fu">addJavadoc</span>(<span class="st">"<p>Use {@link #delete($T)} to delete the entire</span><span class="ch">\n</span><span class="st">"</span>
+ <span class="st">"conversation for all participants.</span><span class="ch">\n</span><span class="st">"</span>, Conversation.<span class="fu">class</span>)
.<span class="fu">addModifiers</span>(Modifier.<span class="fu">PUBLIC</span>, Modifier.<span class="fu">ABSTRACT</span>)
.<span class="fu">addParameter</span>(Message.<span class="fu">class</span>, <span class="st">"message"</span>)
.<span class="fu">build</span>();</code></pre>
<p>Which generates this:</p>
<pre class="sourceCode java"><code class="sourceCode java"> <span class="co">/**</span>
<span class="co"> * Hides </span><span class="kw">{@code message}</span><span class="co"> from the caller's history. Other</span>
<span class="co"> * participants in the conversation will continue to see the</span>
<span class="co"> * message in their own history unless they also delete it.</span>
<span class="co"> *</span>
<span class="er"> * <p>Use {@link #delete(Conversation)} to delete the entire</span>
<span class="co"> * conversation for all participants.</span>
<span class="co"> */</span>
<span class="dt">void</span> <span class="fu">dismiss</span>(Message message);</code></pre>
<p>Use <code>$T</code> when referencing types in Javadoc to get automatic imports.</p>
<h2 id="download">Download</h2>
<p>Download <a href="https://search.maven.org/remote_content?g=com.squareup&a=javapoet&v=LATEST">the latest .jar</a> or depend via Maven:</p>
<pre class="sourceCode xml"><code class="sourceCode xml"><span class="kw"><dependency></span>
<span class="kw"><groupId></span>com.squareup<span class="kw"></groupId></span>
<span class="kw"><artifactId></span>javapoet<span class="kw"></artifactId></span>
<span class="kw"><version></span>1.0.0<span class="kw"></version></span>
<span class="kw"></dependency></span></code></pre>
<p>or Gradle:</p>
<pre class="groovy"><code>compile 'com.squareup:javapoet:1.0.0'</code></pre>
<p>Snapshots of the development version are available in <a href="https://oss.sonatype.org/content/repositories/snapshots/">Sonatype's <code>snapshots</code> repository</a>.</p>
<h2 id="license">License</h2>
<pre><code>Copyright 2015 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.</code></pre>
<h1 id="javawriter">JavaWriter</h1>
<p>JavaPoet is the successor to <a href="https://github.com/square/javapoet/tree/javawriter_2">JavaWriter</a>. New projects should prefer JavaPoet because it has a stronger code model: it understands types and can manage imports automatically. JavaPoet is also better suited to composition: rather than streaming the contents of a <code>.java</code> file top-to-bottom in a single pass, a file can be assembled as a tree of declarations.</p>
<p>JavaWriter continues to be available in <a href="https://github.com/square/javapoet/tree/javawriter_2">GitHub</a> and <a href="http://search.maven.org/#artifactdetails%7Ccom.squareup%7Cjavawriter%7C2.5.1%7Cjar">Maven Central</a>.</p>