I am dealing with Google Protobuf messages.
Since my needs are to set the fields of an object instance (some of them are Protobuff messages), I wrote a function that extracts through the builder reflection and recreates the message through protobuf-java-format .
Here is the code
for (String aFieldName : objectContentMap.keySet()) {
Object aFieldNameValue = objectContentMap.get(aFieldName);
if (aFieldNameValue != null) {
Field theClassField = this.instance.getField(aFieldName);
ReflectionUtils.makeAccessible(theClassField);
Class<?> classType = theClassField.getType();
if (!classType.isPrimitive() &&
GeneratedMessage.class.isAssignableFrom(classType.getSuperclass())) {
Method method = classType.getMethod("newBuilder");
Object builder = method.invoke(new Object());
if (builder instanceof Builder) {
Builder newBuilder = (Builder)builder;
InputStream asd = new ByteArrayInputStream(((String)aFieldNameValue).getBytes());
protoMapper.merge(asd, newBuilder);
aFieldNameValue = newBuilder.build();
}
}
theClassField.set(recreatedObject, aFieldNameValue);
}
}
This fragment works as intended, but I doubt the string Object builder = method.invoke(new Object());, because when I call static methods, I always set it nullas the actual parameter.
In this case, I have a NullPointerException exception.
Does anyone have any idea why there is a need for an instance in the actual invoke () parameter?
Thanks Dario.
Dario source