Add import using code model

1.5k views Asked by At

I am trying to import a class in my code using code model. This is my code.

JCodeModel model = new JCodeModel();
JClass mapper = model.directClass("com.another.Mapper");
JDefinedClass dc = model._class("com.example.Something");
JMethod method = dc.method(JMod.PUBLIC | JMod.STATIC, Void.TYPE,
        "testMethod");
JBlock executerBlock = method.body();
    executerBlock.directStatement("Mapper.get()");
File file = new File("./src");
file.mkdirs();
model.build(file);

Now I am getting the following class as result.

package com.example;
public class Something {
    public static void testMethod() {
    Mapper.get()
    }
}

But actually i need is,

package com.example;
import com.another.Mapper;
public class Something {
    public static void testMethod() {
    Mapper.get()
    }
}

The import is not coming unless it use. How can i possible to make this import.

1

There are 1 answers

0
John Ericksen On

For Mapper to be added as an import, you will need to call invoke() / staticInvoke() instead of directStatement():

JClass mapper = model.directClass("com.another.Mapper");
JDefinedClass dc = model._class("com.example.Something");
JMethod method = dc.method(JMod.PUBLIC | JMod.STATIC, Void.TYPE, "testMethod");
JBlock executerBlock = method.body();
executerBlock.staticInvoke(mapper, "get");