我正在处理 Google Protobuf 消息。
由于我需要设置对象的实例字段(其中一些是 Protobuff 消息),因此我编写了一个函数,该函数通过反射检索构建器并通过protobuf-java-format重新创建消息。
这是代码
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 ByteArrayInputStream(((String)aFieldNameValue).getBytes());
protoMapper.merge(asd, newBuilder);
aFieldNameValue = newBuilder.build();
}
}
theClassField.set(recreatedObject, aFieldNameValue);
}
}
此代码段按预期工作,但我的疑问在于,Object builder = method.invoke(new Object());
当我调用静态方法时,我总是将null
其作为实际参数。
在这种情况下,我有一个 NullPointerException。
有人知道为什么在 invoke() 实际参数中需要一个实例吗?
谢谢达里奥。