javasun-codemodeljcodemodel

How do I add a generic type parameter to a class which I extend with JCodeModel?


I am playing with JCodeModel and trying to generate a class; thanks to this link I was able to come up with this:

public final class CodeModelTest
{
    private CodeModelTest()
    {
        throw new Error("no instantiation is permitted");
    }

    public static void main(final String... args)
        throws JClassAlreadyExistsException, IOException
    {
        final JCodeModel model = new JCodeModel();

        final JDefinedClass c = model._class("foo.bar.Baz");
        c._extends(BaseParser.class);

        final JMethod method = c.method(JMod.PUBLIC, Rule.class, "someRule");

        method.body()._return(JExpr._null());

        final CodeWriter cw = new OutputStreamCodeWriter(System.out,
            StandardCharsets.UTF_8.displayName());

        model.build(cw);
    }
}

So, this works. The generated code on stdout is:

package foo.bar;

import com.github.fge.grappa.parsers.BaseParser;
import com.github.fge.grappa.rules.Rule;

public class Baz
    extends BaseParser
{
    public Rule someRule() {
        return null;
    }
}

So far so good.

Now, the problem is that I'd like to extends BaseParser<Object> and not BaseParser... And I am unable to figure out how to do that despite quite a few hours of googling around...

How do I do this?


Solution

  • You need to call the narrow method in the builder:

    like

     c._extends(BaseParser.class).narrow(yourClassHere);