javacode-generationjdk-internal-api

How to generate import at compile time?


I am currently doing this with the implementation of com.sun.source.util.Plugin, which has this method for adding the following expression to the import section import java.util.List;:

private void generateImport(CompilationUnitTree compilationUnitTree) {
        var jcCompilationUnit = (JCTree.JCCompilationUnit) compilationUnitTree;
        List<JCTree> imports = jcCompilationUnit.defs.stream()
            .filter(def -> def.hasTag(JCTree.Tag.IMPORT))
            .collect(Collectors.toList());
        JCTree.JCImport classImport = treeMaker.Import(
            treeMaker.Select(
                treeMaker.Ident(names.fromString("java.util")),
                names.fromString("List")
            ),
            false
        );
        imports.add(classImport);
        jcCompilationUnit.defs = List.from(imports);
    }

names - Instance of com.sun.tools.javac.util.Names & treeMaker - Instance of com.sun.tools.javac.tree.TreeMaker

I added my plugin as a dependency to a project with one single A.java, and after the mvn package is done, A.class is missing, I just have an empty target directory.

It seems like my solution is wrong. So the question is: how do I add import <something> to A.java at compile time?

P.S. I was looking for ways to add imports in projects such as Lombok, MapStruct, Spoon and other less well-known, but I did not find anything like it.


Solution

  • This solution works except the part where you ignored the Package declaration. With your solution, generated import statement will be above the package declaration and it cause compilation error. If you arrange the line of the import that you generated then it works. Thanks for the solution.