我正在处理Google Protobuf消息.
由于我的需求来设置一个对象(其中有些是Protobuff消息)的实例字段中,我写道,通过反射检索建设者,并通过一个函数的protobuf-java的格式再现的消息.
这是代码
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");
// Since the method is static, the instance object that undergoes the call is not important, but with "null" I have a NPE...
Object builder = method.invoke(new Object());
if (builder instanceof Builder) {
Builder newBuilder = (Builder)builder;
InputStream asd = new …Run Code Online (Sandbox Code Playgroud)