首發於個人公衆號java
JavaPoet使用指南android
註解系列git
上一篇限於篇幅只介紹了APT,這篇來繼續介紹javapoet,是square公司的開源庫。正如其名,java詩人,經過註解來生成java源文件,一般要使用javapoet這個庫與Filer配合使用。主要和註解配合用來幹掉那些重複的模板代碼(如butterknife 和databinding所作的事情),固然你也能夠使用這個技術讓你的代碼更加的炫酷。github
使用以前要先引入這個庫json
compile 'com.squareup:javapoet:1.7.0'
複製代碼
javapoet是用來生成代碼的,須要藉助數組
經常使用類bash
使用javapoet前須要瞭解8個經常使用類app
類名 | 做用 |
---|---|
MethodSpec | 表明一個構造函數或方法聲明 |
TypeSpec | 表明一個類,接口,或者枚舉聲明 |
FieldSpec | 表明一個成員變量,一個字段聲明 |
JavaFile | 包含一個頂級類的Java文件 |
ParameterSpec | 用來建立參數 |
AnnotationSpec | 用來建立註解 |
ClassName | 用來包裝一個類 |
TypeName | 類型,如在添加返回值類型是使用 TypeName.VOID |
除此以外 JavaPoet提供了一套自定義的字符串格式化規則,經常使用的有S,Nide
格式化規則 | 表示含義 |
---|---|
$L | 字面量 |
$S | 字符串 |
$T | 類、接口 |
$N | 變量 |
下面由淺入深,按部就班的說明用法函數
方法&控制流:
addcode
和 addstatement
對與無需類引入的極簡代碼能夠直接使用addCode
MethodSpec main = MethodSpec.methodBuilder("main")
.addCode(""
+ "int total = 0;\n"
+ "for (int i = 0; i < 10; i++) {\n"
+ " total += i;\n"
+ "}\n")
.build();
複製代碼
生成的是
void main() {
int total = 0;
for (int i = 0; i < 10; i++) {
total += i;
}
}
複製代碼
要是須要import的方法,如上面的.addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
就須要使用.addStatement
來聲明
beginControlFlow
流開啓 addStatement
處理語句 endControlFlow()
流結束
如上面的用流改寫就是
MethodSpec main = MethodSpec.methodBuilder("main")
.addStatement("int total = 0")
.beginControlFlow("for (int i = 0; i < 10; i++)")
.addStatement("total += i")
.endControlFlow()
.build();
複製代碼
佔位符
javapoet裏面提供了佔位符來幫助咱們更好地生成代碼
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();
}
複製代碼
這個就是一個for循環,op負責加減乘除等符號
最大的特色是自動導入包
MethodSpec today = MethodSpec.methodBuilder("today")
.returns(Date.class)
.addStatement("return new $T()", Date.class)
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addMethod(today)
.build();
JavaFile javaFile = JavaFile.builder("com.example.helloworld", helloWorld)
.build();
javaFile.writeTo(System.out);
複製代碼
生成的代碼以下,並且會自動導包
package com.example.helloworld;
import java.util.Date;
public final class HelloWorld {
Date today() {
return new Date();
}
}
複製代碼
好比這樣的代碼塊
public String byteToHex(int b) {
char[] result = new char[2];
result[0] = hexDigit((b >>> 4) & 0xf);
result[1] = hexDigit(b & 0xf);
return new String(result);
}
public char hexDigit(int i) {
return (char) (i < 10 ? i + '0' : i - 10 + 'a');
}
複製代碼
咱們能夠傳遞hexDigit()
來代替。
MethodSpec hexDigit = MethodSpec.methodBuilder("hexDigit")
.addParameter(int.class, "i")
.returns(char.class)
.addStatement("return (char) (i < 10 ? i + '0' : i - 10 + 'a')")
.build();
MethodSpec byteToHex = MethodSpec.methodBuilder("byteToHex")
.addParameter(int.class, "b")
.returns(String.class)
.addStatement("char[] result = new char[2]")
.addStatement("result[0] = $N((b >>> 4) & 0xf)", hexDigit)
.addStatement("result[1] = $N(b & 0xf)", hexDigit)
.addStatement("return new String(result)")
.build();
複製代碼
獲取對應類
有兩種方式:
ClassName.bestGuess(「類全名稱」) 返回ClassName對象,這裏的類全名稱表示的類必需要存在,會自動導入相應的包
ClassName.get(「包名」,」類名」) 返回ClassName對象,不檢查該類是否存在
所以若是使用JavaPoet的話後續代碼重構改變類名每每須要格外注意一點
ClassName hoverboard = ClassName.get("com.mattel", "Hoverboard");
ClassName list = ClassName.get("java.util", "List");
ClassName arrayList = ClassName.get("java.util", "ArrayList");
TypeName listOfHoverboards = ParameterizedTypeName.get(list, hoverboard);
MethodSpec beyond = MethodSpec.methodBuilder("beyond")
.returns(listOfHoverboards)
.addStatement("$T result = new $T<>()", listOfHoverboards, arrayList)
.addStatement("result.add(new $T())", hoverboard)
.addStatement("result.add(new $T())", hoverboard)
.addStatement("result.add(new $T())", hoverboard)
.addStatement("return result")
.build();
複製代碼
而後生成
package com.example.helloworld;
import com.mattel.Hoverboard;
import java.util.ArrayList;
import java.util.List;
public final class HelloWorld {
List<Hoverboard> beyond() {
List<Hoverboard> result = new ArrayList<>();
result.add(new Hoverboard());
result.add(new Hoverboard());
result.add(new Hoverboard());
return result;
}
}
複製代碼
構建類的元素
方法的修飾,如Modifiers.ABSTRACT
MethodSpec flux = MethodSpec.methodBuilder("flux")
.addModifiers(Modifier.ABSTRACT, Modifier.PROTECTED)
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addMethod(flux)
.build();
複製代碼
這將會生成以下代碼
public abstract class HelloWorld {
protected abstract void flux();
}
複製代碼
固然Methods須要和MethodSpec.Builder
配置來增長方法參數、異常、javadoc、註解等。
這個其實也是個函數方法而已,所以能夠使用MethodSpec來生成構造器方法。好比:
MethodSpec flux = MethodSpec.constructorBuilder()
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, "greeting")
.addStatement("this.$N = $N", "greeting", "greeting")
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC)
.addField(String.class, "greeting", Modifier.PRIVATE, Modifier.FINAL)
.addMethod(flux)
.build();
複製代碼
將會生成
public class HelloWorld {
private final String greeting;
public HelloWorld(String greeting) {
this.greeting = greeting;
}
}
複製代碼
以前咱們是經過addstatement
直接設置參數,其實參數也有本身的一個專用類ParameterSpec
,咱們能夠使用ParameterSpec.builder()
來生成參數,而後MethodSpec的addParameter去使用,這樣更加優雅。
ParameterSpec android = ParameterSpec.builder(String.class, "android")
.addModifiers(Modifier.FINAL)
.build();
MethodSpec welcomeOverlords = MethodSpec.methodBuilder("welcomeOverlords")
.addParameter(android)
.addParameter(String.class, "robot", Modifier.FINAL)
.build();
複製代碼
生成的代碼
void welcomeOverlords(final String android, final String robot) {
}
複製代碼
稍微複雜點的類型 好比泛型 、Map之類的,須要瞭解下JavaPoet定義的幾種專門描述類型的類
常見的有分類 | 生成的類型 | JavaPoet 寫法 | 也能夠這麼寫 (等效的 Java 寫法) |
---|---|---|---|
內置類型 | int | TypeName.INT | int.class |
數組類型 | int[] | ArrayTypeName.of(int.class) | int[].class |
須要引入包名的類型 | java.io.File | ClassName.get(「java.io」, 「File」) | java.io.File.class |
參數化類型 (ParameterizedType | List | ParameterizedTypeName.get(List.class, String.class) | - |
類型變量 (WildcardType) 用於聲明泛型 | T | TypeVariableName.get(「T」) | - |
通配符類型 | ? extends String | WildcardTypeName.subtypeOf(String.class) | - |
/*
*Build input type, format as :
*Map<String, Class<? extends IRouteGroup>>
*/
ParameterizedTypeName inputMapTypeOfRoot = ParameterizedTypeName.get(
ClassName.get(Map.class),
ClassName.get(String.class),
ParameterizedTypeName.get(
ClassName.get(Class.class),
WildcardTypeName.subtypeOf(ClassName.get(type_IRouteGroup))
)
);
/*
*Map<String, RouteMeta>
*/
ParameterizedTypeName inputMapTypeOfGroup = ParameterizedTypeName.get(
ClassName.get(Map.class),
ClassName.get(String.class),
ClassName.get(RouteMeta.class)
);
/*
*Build input param name.
*/
ParameterSpec rootParamSpec = ParameterSpec.builder(inputMapTypeOfRoot, "routes").build();
ParameterSpec groupParamSpec = ParameterSpec.builder(inputMapTypeOfGroup, "atlas").build();
複製代碼
生成參數類型
public class ARouter$$Root$$app implements IRouteRoot {
@Override
public void loadInto(Map<String, Class<? extends IRouteGroup>> routes) {
routes.put("service", ARouter$$Group$$service.class);
routes.put("test", ARouter$$Group$$test.class);
}
}
public class ARouter$$Group$$service implements IRouteGroup {
@Override
public void loadInto(Map<String, RouteMeta> atlas) {
atlas.put("/service/hello", RouteMeta.build(RouteType.PROVIDER, HelloServiceImpl.class, "/service/hello", "service", null, -1, -2147483648));
atlas.put("/service/json", RouteMeta.build(RouteType.PROVIDER, JsonServiceImpl.class, "/service/json", "service", null, -1, -2147483648));
atlas.put("/service/single", RouteMeta.build(RouteType.PROVIDER, SingleService.class, "/service/single", "service", null, -1, -2147483648));
}
}
複製代碼
能夠使用FieldSpec去聲明字段,而後加到Method中處理
FieldSpec android = FieldSpec.builder(String.class, "android")
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC)
.addField(android)
.addField(String.class, "robot", Modifier.PRIVATE, Modifier.FINAL)
.build();
複製代碼
而後生成代碼
public class HelloWorld {
private final String android;
private final String robot;
}
複製代碼
一般Builder能夠更加詳細的建立字段的內容,好比javadoc、annotations或者初始化字段參數等,如:
FieldSpec android = FieldSpec.builder(String.class, "android")
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
.initializer("$S + $L", "Lollipop v.", 5.0d)
.build();
複製代碼
對應生成的代碼
private final String android = "Lollipop v." + 5.0;
複製代碼
接口方法必須是PUBLIC ABSTRACT而且接口字段必須是PUBLIC STATIC FINAL ,使用TypeSpec.interfaceBuilder
以下
TypeSpec helloWorld = TypeSpec.interfaceBuilder("HelloWorld")
.addModifiers(Modifier.PUBLIC)
.addField(FieldSpec.builder(String.class, "ONLY_THING_THAT_IS_CONSTANT")
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("$S", "change")
.build())
.addMethod(MethodSpec.methodBuilder("beep")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build())
.build();
複製代碼
生成的代碼以下
public interface HelloWorld {
String ONLY_THING_THAT_IS_CONSTANT = "change";
void beep();
}
複製代碼
接口代碼
package com.test.javapoet;
public interface TestInterface<T> {
void test(T testPara);
}
複製代碼
父類代碼
public class TestExtendesClass {
}
複製代碼
使用javapoet實現接口而且繼承父類
final ClassName InterfaceName = ClassName.get("com.test.javapoet","TestInterface");
ClassName superinterface = ClassName.bestGuess("com.test.javapoet.TestClass");
//ClassName superinterface = ClassName.get("com.test.javapoet","aa");
TypeSpec.Builder spec = TypeSpec.classBuilder("TestImpl")
.addModifiers(Modifier.PUBLIC)
// 添加接口,ParameterizedTypeName的參數1是接口,參數2是接口的泛型
.addSuperinterface(ParameterizedTypeName.get(InterfaceName, superinterface))
//使用ClassName.bestGuess會自動導入包
.superclass(ClassName.bestGuess("com.zs.javapoet.test.TestExtendesClass"));
MethodSpec.Builder methodSpec = MethodSpec.methodBuilder("test")
.addAnnotation(Override.class)
.returns(TypeName.VOID)
.addParameter(superinterface, "testPara")
.addStatement("System.out.println(hello)" );
TypeSpec typeSpec = spec.addMethod(methodSpec.build()).build();
JavaFile file = JavaFile.builder("com.zs.javapoet", typeSpec).build();
file.writeTo(System.out);
複製代碼
生成代碼
package com.test.javapoet;
import com.zs.javapoet.test.TestExtendesClass;
import java.lang.Override;
public class TestImpl extends TestExtendesClass implements TestInterface<TestClass> {
@Override
void test(TestClass testPara) {
System.out.println(hello);
}
}
複製代碼
使用TypeSpec.enumBuilder
來建立,使用addEnumConstant
來添加
TypeSpec helloWorld = TypeSpec.enumBuilder("Roshambo")
.addModifiers(Modifier.PUBLIC)
.addEnumConstant("ROCK")
.addEnumConstant("SCISSORS")
.addEnumConstant("PAPER")
.build();
複製代碼
生成的代碼
public enum Roshambo {
ROCK,
SCISSORS,
PAPER
}
複製代碼
更復雜的類型也能夠支持,如重寫、註解等
TypeSpec helloWorld = TypeSpec.enumBuilder("Roshambo")
.addModifiers(Modifier.PUBLIC)
.addEnumConstant("ROCK", TypeSpec.anonymousClassBuilder("$S", "fist")
.addMethod(MethodSpec.methodBuilder("toString")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.addStatement("return $S", "avalanche!")
.build())
.build())
.addEnumConstant("SCISSORS", TypeSpec.anonymousClassBuilder("$S", "peace")
.build())
.addEnumConstant("PAPER", TypeSpec.anonymousClassBuilder("$S", "flat")
.build())
.addField(String.class, "handsign", Modifier.PRIVATE, Modifier.FINAL)
.addMethod(MethodSpec.constructorBuilder()
.addParameter(String.class, "handsign")
.addStatement("this.$N = $N", "handsign", "handsign")
.build())
.build();
複製代碼
生成代碼
public enum Roshambo {
ROCK("fist") {
@Override
public void toString() {
return "avalanche!";
}
},
SCISSORS("peace"),
PAPER("flat");
private final String handsign;
Roshambo(String handsign) {
this.handsign = handsign;
}
}
複製代碼
須要使用Type.anonymousInnerClass("")
,一般能夠使用$L佔位符來指代
TypeSpec comparator = TypeSpec.anonymousClassBuilder("")
.addSuperinterface(ParameterizedTypeName.get(Comparator.class, String.class))
.addMethod(MethodSpec.methodBuilder("compare")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.addParameter(String.class, "a")
.addParameter(String.class, "b")
.returns(int.class)
.addStatement("return $N.length() - $N.length()", "a", "b")
.build())
.build();
TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
.addMethod(MethodSpec.methodBuilder("sortByLength")
.addParameter(ParameterizedTypeName.get(List.class, String.class), "strings")
.addStatement("$T.sort($N, $L)", Collections.class, "strings", comparator)
.build())
.build();
複製代碼
生成代碼
void sortByLength(List<String> strings) {
Collections.sort(strings, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return a.length() - b.length();
}
});
}
複製代碼
定義匿名內部類的一個特別棘手的問題是參數的構造。在上面的代碼中咱們傳遞了不帶參數的空字符串。TypeSpec.anonymousClassBuilder("")。
註解使用起來比較簡單
MethodSpec toString = MethodSpec.methodBuilder("toString")
.addAnnotation(Override.class)
.returns(String.class)
.addModifiers(Modifier.PUBLIC)
.addStatement("return $S", "Hoverboard")
.build();
複製代碼
生成代碼
@Override
public String toString() {
return "Hoverboard";
}
複製代碼
經過AnnotationSpec.builder()
能夠對註解設置屬性:
MethodSpec logRecord = MethodSpec.methodBuilder("recordEvent")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addAnnotation(AnnotationSpec.builder(Headers.class)
.addMember("accept", "$S", "application/json; charset=utf-8")
.addMember("userAgent", "$S", "Square Cash")
.build())
.addParameter(LogRecord.class, "logRecord")
.returns(LogReceipt.class)
.build();
複製代碼
代碼生成以下
@Headers(
accept = "application/json; charset=utf-8",
userAgent = "Square Cash"
)
LogReceipt recordEvent(LogRecord logRecord);
複製代碼
註解一樣能夠註解其餘註解,經過$L引用如
MethodSpec logRecord = MethodSpec.methodBuilder("recordEvent")
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.addAnnotation(AnnotationSpec.builder(HeaderList.class)
.addMember("value", "$L", AnnotationSpec.builder(Header.class)
.addMember("name", "$S", "Accept")
.addMember("value", "$S", "application/json; charset=utf-8")
.build())
.addMember("value", "$L", AnnotationSpec.builder(Header.class)
.addMember("name", "$S", "User-Agent")
.addMember("value", "$S", "Square Cash")
.build())
.build())
.addParameter(LogRecord.class, "logRecord")
.returns(LogReceipt.class)
.build();
複製代碼
生成代碼
@HeaderList({
@Header(name = "Accept", value = "application/json; charset=utf-8"),
@Header(name = "User-Agent", value = "Square Cash")
})
LogReceipt recordEvent(LogRecord logRecord);
複製代碼
註釋
在javapoet以前有javawriter,但javapoet有着更強大的代碼模型,而且對類的理解更加到位,所以推薦使用javapoet
歡迎關注個人公衆號,一塊兒學習,共同提升~
複製代碼