我想生成一些代码,如下所示:
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)
...
感谢。
答案 0 :(得分: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>() {
}
;
}