0

我想生成一些如下代码:

AbstractSomeClass<?> someClassObj = new AbstractSomeClass<MyConcreteType> {
    ...
}

我尝试了以下方法:

JDefinedClass anonymousSomeClass = codeModel.anonymousClass(AbstractSomeClass.class);
...
conditionalBody.decl(anonymousSomeClass, "someClassObj", JExpr._new(anonymousSomeClass.narrow(jClass)));

下面出现异常,由“anonymousSomeClass.narrow(jClass)”引起。如果我删除'.narrow(jClass)',一切都会好起来的。

java.lang.NullPointerException
    at com.sun.codemodel.JDefinedClass.outer(JDefinedClass.java:776)
    at com.sun.codemodel.JFormatter.t(JFormatter.java:280)
    at com.sun.codemodel.JNarrowedClass.generate(JNarrowedClass.java:143)
    at com.sun.codemodel.JFormatter.g(JFormatter.java:350)
    at com.sun.codemodel.JInvocation.generate(JInvocation.java:173)
    at com.sun.codemodel.JFormatter.g(JFormatter.java:350)
    at com.sun.codemodel.JVar.bind(JVar.java:212)
    at com.sun.codemodel.JFormatter.b(JFormatter.java:396)
    at com.sun.codemodel.JVar.declare(JVar.java:216)
        ...

谢谢。

4

1 回答 1

2

这似乎是 CodeModel 处理匿名类及其所有权的方式中的一个错误。然而,有一种方法可以解决这个问题,通过在将其视为匿名类型之前缩小类:

    JDefinedClass tester = codeModel._class("Tester");

    JClass jClass = codeModel.ref(Reference.class);
    JClass unnarrowed =  codeModel.ref(AbstractSomeClass.class).narrow(codeModel.wildcard());
    JClass narrowed = codeModel.ref(AbstractSomeClass.class).narrow(jClass);

    JClass anonymous = codeModel.anonymousClass(narrowed);

    tester.field(JMod.PUBLIC, unnarrowed, "someClassObj", JExpr._new(anonymous));

给出:

import test.Tester.AbstractSomeClass;

public class Tester {

    public test.Tester.AbstractSomeClass<?> someClassObj = new AbstractSomeClass<Reference>() {


    }
    ;

}
于 2014-10-07T17:58:12.117 回答