Darn, there's only one snag. I need the protobuf package name, not the java package classname, in order to construct the message name that corresponds to the result of full_name() in the C++ generated code. Of course, I can *make *them the same thing, but I'm not finding any way to interrogate the class to find out the package to which it belongs. john
On Mon, Jul 9, 2018 at 5:17 PM John Lilley <[email protected]> wrote: > Success! This works nicely (although, lacking polish) > > public class MessageFactory { > > private final Map<String,Message> defaultMessages = new HashMap<>(); > > public void add(Class wrapperClass) { > for (Class nestedClass : wrapperClass.getDeclaredClasses()) { > if (!Message.class.isAssignableFrom(nestedClass)) { > continue; > } > try { > String fullName = wrapperClass.getSimpleName() + "." + > nestedClass.getSimpleName(); > Message message = (Message)nestedClass.getMethod( > "getDefaultInstance").invoke(null); > defaultMessages.put(fullName, message); > } catch (Exception ex) { > ex.printStackTrace(); > } > } > } > > public Message.Builder getBuilder(String fullName) { > Message message = defaultMessages.get(fullName); > if (message == null) { > throw new IllegalArgumentException("Unknown message name '" + > fullName + "'"); > } > return message.newBuilderForType(); > } > > public Message createMessage(String fullName, InputStream is) throws > Exception { > Message.Builder builder = getBuilder(fullName); > CodedInputStream cis = CodedInputStream.newInstance(is); > return builder.mergeFrom(cis).build(); > } > > > public Message createMessage(String fullName, byte[] buffer) throws > Exception { > return createMessage(fullName, new ByteArrayInputStream(buffer)); > } > } > > > > -- > 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 [email protected]. > To post to this group, send email to [email protected]. > Visit this group at https://groups.google.com/group/protobuf. > For more options, visit https://groups.google.com/d/optout. > -- 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 [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/protobuf. For more options, visit https://groups.google.com/d/optout.
