Search code examples
javasun-codemodel

Sun CodeModel using Class with JInvocation.arg


I'm using sun's code model (2.4.1) classes to generate code. How do I pass a Class to JInvocation.arg? The code I am trying to generate is:

JAXBContext jc;
jc = JAXBContext.newInstance(NaturalLanguageUsage.class);

The code I am running is:

JClass importJAXBContext = codeModel.directClass(javax.xml.bind.JAXBContext.class.toString());
JType typeJAXBContext = codeModel._ref(javax.xml.bind.JAXBContext.class);
JVar varJc = block.decl(typeJAXBContext, "jc");

JInvocation invokeJAXBContext = block.staticInvoke(importJAXBContext, "newInstance");
invokeJAXBContext.arg(??); // how do I pass NaturalLanguageUsage.class

What I would like to produce:

JAXBContext jc;
jc = JAXBContext.newInstance(NaturalLanguageUsage.class);

or even better:

JAXBContext jc = JAXBContext.newInstance(NaturalLanguageUsage.class);

Solution

  •     JClass importJAXBContext = codeModel.ref(javax.xml.bind.JAXBContext.class);
        JVar varJc = block.decl(importJAXBContext, "jc");
    
        JClass naturalLangClassRef = codeModel.ref(NaturalLanguageUsage.class);
    
        JInvocation invokeJAXBContext = importJAXBContext.staticInvoke("newInstance");
        invokeJAXBContext.arg(naturalLangClassRef.dotclass());
    
        block.assign(varJc, invokeJAXBContext);
    

    To produce declaration and assignment in one line:

        JVar varJc = block.decl(importJAXBContext, "jc", invokeJAXBContext);