fge
fge

Reputation: 121820

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?

Upvotes: 0

Views: 595

Answers (2)

abedurftig
abedurftig

Reputation: 1248

Try this:

JClass type = model.ref(BaseParser.class).narrow(Object.class);
c._extends(type);

Hope this helps.

Upvotes: 0

You need to call the narrow method in the builder:

like

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

Upvotes: 0

Related Questions