I created a Java program, which needs to be able to update fields in nested Messages. The problem is that if I have a Message.Builder and within this builder I have a repeated Message, I cannot find a general method in the GPB libraries to change this into a Builder which is automatically part of the parent builder.
I solved this with the following code: private Message.Builder createRepeatedBuilder(Message.Builder builder, FieldDescriptor fieldDescriptor) { // Unfortunately I cannot find any general method to create a builder for a repeated message. // Therefore I use reflection myself by using the field name and convert it to add<name>Builder. // E.g. add MergeElementsBuilder String name = fieldDescriptor.getName(); if (name.contains("_")) { name = name.substring(0, 1).toUpperCase() + name.substring(1); } while (name.contains("_")) { name = name.substring(0, name.indexOf("_")) + name.substring(name.indexOf("_") + 1, name.indexOf("_") + 2).toUpperCase() + name.substring(name.indexOf("_") + 2); } name = "add" + name + "Builder"; // propertiesBuilder = ((DataObjectMerge.Builder) mainBuilder).addMergeElementsBuilder(0); // Reflection try { if (parent == null) { Method method = mainBuilder.getClass().getMethod(name); return (Message.Builder) method.invoke(mainBuilder); } else { Method method = builder.getClass().getMethod(name); return (Message.Builder) method.invoke(builder); } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } return null; } -- You received this message because you are subscribed to the Google Groups "Protocol Buffers" group. To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+unsubscr...@googlegroups.com. To post to this group, send email to protobuf@googlegroups.com. Visit this group at http://groups.google.com/group/protobuf. For more options, visit https://groups.google.com/groups/opt_out.