square / javapoet

A Java API for generating .java source files.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

When using JavaFile builder Import statement for Array of Class is Wrong

prakharporwal opened this issue · comments

If I have use a String Array (String[]) in the code and create a JavaFile from package com.squareup.javapoet
The JavaFile has

import java.lang.String[];

instead of

import java.lang.String;

I am using a the JavaFile builder

JavaFile.builder("com.mypakage.some", typeSpec)
                .addStaticImport(ClassName.bestGuess("org.MyClass.Name"), "*")
                .build();

Would need help on how to handle the import type ?
Or is it an issue from the JavaPoet side ?

Are you using ArrayTypeName? Seems like you're creating a ClassName with a simple name that contains the array brackets.

In the future, please include a self-contained, executable, minimal example that illustrates the problem. We don't want to have to play a guessing game as to what you are doing. A failing test case completely removes the ambiguity of what you are doing and what you expect the outcome to be.

Apologise on missing an example to clarify

I am trying to build a Class which has a method which gets assigned a String Array from a service.
But the imports generated for the Class for String[] is wrong.
I am using Class.bestGuess to resolve class from String name .

Here is example of what I am doing.

TypeName stringArray = ClassName.bestGuess("java.lang.String[]");
TypeName  someService = ClassName.bestGuess("com.org.MyService");

MethodSpec main = MethodSpec.methodBuilder("main")
    .addModifiers(Modifier.PUBLIC)
    .returns(void.class)
    .addStatement("$T $S = $L.$L)", stringArray, "myVar", someService, "stringArrayMethod" )
    .build();

TypeSpec helloWorld = TypeSpec.classBuilder("StringService")
    .addModifiers(Modifier.PUBLIC)
    .addMethod(main)
    .build();

JavaFile javaFile = JavaFile.builder("com.mypakage.some", typeSpec)
                .addStaticImport(ClassName.bestGuess("com.org.MyService"), "*")
                .build();

javaFile.writeTo(System.out);

Expecting this

package com.mypakage.some;

import java.lang.String;  // { Getting ` import java.lang.String[];`  }
import static com.org.MyService;

public void main(){
       String[] myVar = MyService.stringArrayMethod();
}

And as I can see you have guessed it right. I am was using ClassName Instead of ArrayTypeName.
Making that change Solves the Problem.

From Jake above:

Are you using ArrayTypeName? Seems like you're creating a ClassName with a simple name that contains the array brackets.

And you're saying you're using:

TypeName stringArray = ClassName.bestGuess("java.lang.String[]");

ClassName.bestGuess() returns a ClassName, not any TypeName. You'll want an ArrayTypeName.of(ClassName.bestGuess("java.lang.String")) or ArrayTypeName.of(ClassName.get(String.class)) or ArrayTypeName.get(String[].class).