基于 javapoet 实现 Java 代码文件生成

当我们使用APT技术,或者想生成Java代码可以使用javapoet,他可以非常方便我们实现代码生成,用法也非常简单。

引入依赖

implementation 'com.squareup:javapoet:1.7.0'

代码

public class JavapoetTest {

    public static void main(String[] args) throws IOException {
        ClassName className = ClassName.bestGuess("com.taoweiji.User");

        TypeSpec.Builder userTypeSpec = TypeSpec.classBuilder(className)
                .addModifiers(Modifier.PUBLIC).superclass(Serializable.class);

        // private int id = 0;
        FieldSpec idFieldSpec = FieldSpec.builder(int.class, "id", Modifier.PRIVATE)
                .initializer("0").build();
        userTypeSpec.addField(idFieldSpec);

        // private String name = "";
        FieldSpec nameFieldSpec = FieldSpec.builder(String.class, "name", Modifier.PRIVATE)
                .initializer("\"\"").build();
        userTypeSpec.addField(nameFieldSpec);

        //public User(int id, String name) {
        //    this.id = id;
        //    this.name = name;
        //}
        MethodSpec constructor = MethodSpec.constructorBuilder()
                .addModifiers(Modifier.PUBLIC)
                .addParameter(int.class,"id")
                .addParameter(String.class,"name")
                .addStatement("this.id = id")
                .addStatement("this.name = name")
                .build();
        userTypeSpec.addMethod(constructor);

        //public void setId(int id) {
        //    this.id = id;
        //}
        MethodSpec setIdMethodSpec = MethodSpec.methodBuilder("setId")
                .addModifiers(Modifier.PUBLIC)
                .addParameter(int.class,"id")
                .addStatement("this.id = id")
                .build();
        userTypeSpec.addMethod(setIdMethodSpec);

        //public int getId() {
        //    return id;
        //}
        MethodSpec getIdMethodSpec = MethodSpec.methodBuilder("getId")
                .addModifiers(Modifier.PUBLIC)
                .returns(int.class)
                .addStatement("return id")
                .build();
        userTypeSpec.addMethod(getIdMethodSpec);


        JavaFile javaFile = JavaFile.builder("com.taoweiji",userTypeSpec.build()).build();
        javaFile.writeTo(System.out);

        // javaFile.writeTo(new File("/tmp"));
    }
}

输出结果

package com.taoweiji;
import java.io.Serializable;
import java.lang.String;
public class User extends Serializable {
  private int id = 0;
  private String name = "";
  public User(int id, String name) {
    this.id = id;
    this.name = name;
  }
  public void setId(int id) {
    this.id = id;
  }
  public int getId() {
    return id;
  }
}
更多资料

基于 KotlinPoet 实现 Kotlin
https://blog.csdn.net/l540675759/article/details/82931785
https://blog.csdn.net/Gdeer/article/details/88927821

你可能感兴趣的:(java,android)