w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to create import in generated java fils?

Filtering imports from existing code isn't trivial; imagine you have two classes with the same name but different package.

My usual approach is to have a helper class which manages the imports for me. In the generator, I can

String type = importSet.add(Foo.class);

type is then used in the method to access the type. The import set collects all imports and handles duplicates.

For this to work, you need this "main loop":

importSet = new ImportSet();
String body = generateClass();


i.e. you need to generate all the code for the class itself (collecting the imports as you go) first. Then you write the imports to the file and after that the generated class body.

If you want to change the sources, I suggest to use the Eclipse Java compiler because it can give you the AST of the code. You can then apply various transformations on this tree. I have an example in my blog how to get the AST.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.