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() 実パラメータにインスタンスが必要な理由を誰か知っていますか?
ありがとうダリオ。