square / javapoet

A Java API for generating .java source files.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

can not auto import class on method definition?

coderstory opened this issue · comments

on readme

Use $T when referencing types in Javadoc to get automatic imports.

can import automatically only use $T?

exclusive annotation,method definition ?

public static final class Entity2 {
  @com.fasterxml.jackson.annotation.JsonProperty("id")
  private java.lang.Long id;

  @com.fasterxml.jackson.annotation.JsonProperty("Attribute3")
  private java.lang.String Attribute3;

  @com.fasterxml.jackson.annotation.JsonProperty("Attribute2")
  private java.lang.Long Attribute2;

  public java.lang.Long getId() {
    return id;
  }

  public void setId(java.lang.Long id) {
    this.id = id;
  }

  public java.lang.String getAttribute3() {
    return Attribute3;
  }

  public void setAttribute3(java.lang.String Attribute3) {
    this.Attribute3 = Attribute3;
  }

  public java.lang.Long getAttribute2() {
    return Attribute2;
  }

  public void setAttribute2(java.lang.Long Attribute2) {
    this.Attribute2 = Attribute2;
  }
}

code to build

    private void buildGetAndSet(TypeSpec.Builder clazz, TypeName type, String name) {
        String bigName = name.substring(0, 1).toUpperCase(Locale.ROOT) + name.substring(1);
        MethodSpec.Builder getBuilder = MethodSpec.methodBuilder("get" + bigName)
                .addModifiers(Modifier.PUBLIC)
                .returns(type);
        getBuilder.addStatement("return $N", name);
        clazz.addMethod(getBuilder.build());
        MethodSpec.Builder setBuilder = MethodSpec.methodBuilder("set" + bigName)
                .addModifiers(Modifier.PUBLIC)
                .addParameter(type, name)
                .returns(void.class);
        setBuilder.addStatement("this.$1N = $1N", name);
        clazz.addMethod(setBuilder.build());
    }

Maybe I don't understand you very well, but I'm trying to answer your question.

Looks like you're calling toString on the TypeSpec rather than adding to a FileSpec. Imports are a file property and not a type property thus you need to ensure you create a FileSpec into which all imports can be aggregated.