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

最佳答案

假设您可以填写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() {
    }
}

关于java - 如何使用sun-codemodel生成匿名类?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16530397/

10-11 20:49