Tobias Neef | 25 Jul 2012 13:20
Picon

Re: How to convert protobuf with same structure in java

Hi Oliver,

oh I missed that one. Thanks!

Setting the FieldDescriptors on the target message wasn't the way to
go. Because the FD contains a lot of information specific to the
enclosing type. I solved the issue by using a reflection based
approach which is not that nice but will work in the beginning.

public static <T extends Message> T commandToEvent(Message command,
			Class<T> clazz) {
		try {
			Method m = clazz.getMethod("newBuilder");
			Builder builder = (Builder) m.invoke(null);

			Map<FieldDescriptor, Object> commandFields = command.getAllFields();
			for(Entry<FieldDescriptor, Object> e : commandFields.entrySet()) {
				// Construct JavaBean setter for property
				String fieldName = e.getKey().getName();
				char firstChar = Character.toUpperCase(fieldName.charAt(0));
				String setMethod = "set"+firstChar+fieldName.substring(1);		
				
				// invoke setter with value from the event message
				Method setter = builder.getClass().getMethod(setMethod,
e.getValue().getClass());
				setter.invoke(builder, e.getValue());
			}	

			return (T)builder.build();
		} catch (Exception e) {
			Throwables.propagate(e);				
		}		
		return null;
	}

On Wed, Jul 25, 2012 at 1:08 AM, Oliver Jowett <oliver.jowett <at> gmail.com> wrote:
> On Tue, Jul 24, 2012 at 3:55 PM, Tobias Neef <tobnee <at> gmail.com> wrote:
>
>> I try to convert the Java representation of a protobuf message into another
>> message with the same fields (ordering, names, types). I try to do it the
>> following way but this ends in a java.lang.InstantiationException:
>>
>> public static <T extends GeneratedMessage> T commandToEvent(GeneratedMessage
>> command,
>> Class<T> clazz) {
>> try {
>> Builder builder = clazz.newInstance().newBuilderForType();
>
> Generated message classes don't have a public ctor, so newInstance() will fail.
> Pass the default instance of the message class, not the class itself,
> to identify the message type to build?
>
> Oliver

--

-- 
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To post to this group, send email to protobuf <at> googlegroups.com.
To unsubscribe from this group, send email to protobuf+unsubscribe <at> googlegroups.com.
For more options, visit this group at http://groups.google.com/group/protobuf?hl=en.


Gmane