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)」
また、次のようにも述べて
います。 ."

これは、基になるメソッドが静的ではないことを意味します。ただし、それが静的であるかどうかを確認していますが、正しくありません。

于 2013-04-25T13:34:05.057 に答える