0

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?

fge
  • 119,121
  • 33
  • 254
  • 329

2 Answers2

0

You need to call the narrow method in the builder:

like

 c._extends(BaseParser.class).narrow(yourClassHere);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • No dice... At least it doesn't work here. Does it work for you? – fge Mar 15 '16 at 21:40
  • OK, thanks to your post and other reading around, I found out. What you actually want here is to narrow the _extended class_, not the main one. The solution is therefore to use the `JCodeModel` instance to generate this: `model.ref(BaseParser.class).narrow(Object.class)` – fge Mar 15 '16 at 21:55
0

Try this:

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

Hope this helps.

abedurftig
  • 1,118
  • 1
  • 12
  • 24