/**
* Define the write method.
*/
private void defineWriteUnionMethod()
{
MethodDefinition write = new MethodDefinition(
a(PUBLIC),
"write",
null,
arg("struct", structType),
arg("protocol", TProtocol.class)
);
classDefinition.addMethod(write);
// TProtocolWriter writer = new TProtocolWriter(protocol);
write.addLocalVariable(type(TProtocolWriter.class), "writer");
write.newObject(TProtocolWriter.class);
write.dup();
write.loadVariable("protocol");
write.invokeConstructor(type(TProtocolWriter.class), type(TProtocol.class));
write.storeVariable("writer");
LocalVariableDefinition protocol = write.getLocalVariable("writer");
// protocol.writeStructBegin("bonk");
write.loadVariable(protocol)
.loadConstant(metadata.getStructName())
.invokeVirtual(TProtocolWriter.class, "writeStructBegin", void.class, String.class);
// find the @ThriftUnionId field
ThriftFieldMetadata idField = getOnlyElement(metadata.getFields(THRIFT_UNION_ID));
// load its value
loadFieldValue(write, idField);
// switch(fieldId)
List<CaseStatement> cases = new ArrayList<>();
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
cases.add(caseStatement(field.getId(), field.getName() + "-write-field"));
}
write.switchStatement("default-write", cases);
// write fields
for (ThriftFieldMetadata field : metadata.getFields(THRIFT_FIELD)) {
write.visitLabel(field.getName() + "-write-field");
writeField(write, protocol, field);
write.gotoLabel("default-write");
}
write.visitLabel("default-write")
.loadVariable(protocol)
.invokeVirtual(TProtocolWriter.class, "writeStructEnd", void.class);
write.ret();
}