2

我正在尝试使用 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));
4

1 回答 1

6

假设您可以填写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() {
    }
}
于 2013-12-03T18:58:08.440 回答