如何将泛型类型参数添加到使用 JCodeModel 扩展的 class?

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

我正在玩 JCodeModel and trying to generate a class; thanks to this link 我想出了这个:

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);
    }
}

所以,这行得通。 stdout 上生成的代码是:

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;
    }
}

到目前为止一切顺利。

现在,问题是我想 extends BaseParser<Object> 而不是 BaseParser...尽管在谷歌上搜索了好几个小时,我还是无法弄清楚该怎么做...

我该怎么做?

您需要调用builder中的narrow方法:

喜欢

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

试试这个:

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

希望对您有所帮助。