Question

I'm trying to generate the code below using codemodel, but I have no idea how to create the anonymous class syntax. I can't find it in the codemodel documentation (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();
        }
    }
};

I can use the code below to instantiate the variable "ContentProducer" but I don't know how to implement the method writeTo next to the constructor.

JClass ContentProducer = events.ref(org.apache.http.entity.ContentProducer.class);
JVar contentProducer = tryBlock.body().decl(ContentProducer, "contentProducer").init(JExpr._new(ContentProducer));
Was it helpful?

Solution

Assuming you can fill in the writeTo() method body, what you will need to do is implement the class as an anonymous inner class like so:

JDefinedClass anonymousContentProducer = codeModel.anonymousClass(ContentProducer.class);

JBlock methodBody = anonymousContentProducer.method(JMod.PUBLIC, codeModel.VOID, "writeTo").body();

body.decl(anonymousContentProducer, "contentProducer", JExpr._new(anonymousContentProducer));

which outputs:

ContentProducer contentProducer = new ContentProducer() {
    public void writeTo() {
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top