我正在尝试使用codemodel生成下面的代码,但我不知道如何创建匿名类语法。我在codemodel文档(https://codemodel.java.net/nonav/apidocs/index.html?com/sun/codemodel)
中找不到它ContentProducer cp = new ContentProducer() {
public void writeTo(OutputStream outstream) {
try {
Writer writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<product><descricao>Update de descricao</descricao></product>");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
};
我可以使用下面的代码来实例化变量“ContentProducer”,但我不知道如何在构造函数旁边实现writeTo方法。
JClass ContentProducer = events.ref(org.apache.http.entity.ContentProducer.class);
JVar contentProducer = tryBlock.body().decl(ContentProducer, "contentProducer").init(JExpr._new(ContentProducer));
答案 0 :(得分:5)
假设您可以填写writeTo()
方法体,您需要做的是将类实现为匿名内部类,如下所示:
JDefinedClass anonymousContentProducer = codeModel.anonymousClass(ContentProducer.class);
JBlock methodBody = anonymousContentProducer.method(JMod.PUBLIC, codeModel.VOID, "writeTo").body();
body.decl(anonymousContentProducer, "contentProducer", JExpr._new(anonymousContentProducer));
输出:
ContentProducer contentProducer = new ContentProducer() {
public void writeTo() {
}
}