5

我正在处理 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() 实际参数中需要一个实例吗?

谢谢达里奥。

4

1 回答 1

0

Method的javadoc说Method.invoke方法签名是:
“invoke(Object obj,Object ... args)”
它还说:
“如果底层方法是静态的,那么指定的obj参数将被忽略。它可能是null 。”

这意味着您的基础方法不是静态的。但是,您正在检查它是否是静态的,这是不正确的。

于 2013-04-25T13:34:05.057 回答