javasun-codemodel

Codemodel does not generate static import


JCodeModel generates an import statement in place of an import static. For example I have a class that has import nz.co.cloudm.cloudserv.api.pojos.core.file.attachment.Attachment.Status instead of import static nz.co.cloudm.cloudserv.api.pojos.core.file.attachment.Attachment.Status so the compiler throws an error. The class Status is an inner enum that lives in the Attachment class as you can see in the import statement.

Do you know any way I can achieve an import static using code model?

Or otherwise how make the member to use the class qualified name?

private nz.co.cloudm.cloudserv.api.pojos.core.file.attachment.Attachment.Status status;

Solution

  • I'm not sure codemodel has the ability to define static imports, as it's an older library. You can use the enum though just through the ref() method since static imports are really just a programmer's convenience:

    public class Tester {
    
        public enum Status{
            ONE, TWO;
        }
    
        public static void main(String[] args) throws JClassAlreadyExistsException, IOException {
            JCodeModel codeModel = new JCodeModel();
    
            JClass ref = codeModel.ref(Status.class);
    
            JDefinedClass outputClass = codeModel._class("Output");
    
            outputClass.field(JMod.PRIVATE, ref, "status", ref.staticRef(Status.ONE.name()));
    
            codeModel.build(new StdOutCodeWriter());
        }
    }
    

    Outputs:

    public class Output {
        private test.Tester.Status status = test.Tester.Status.ONE;
    }