Calling a static method via Method.invoke () gave me NPE

I am dealing with Google Protobuf messages.

Since my needs are to set the fields of an object instance (some of them are Protobuff messages), I wrote a function that extracts through the builder reflection and recreates the message through protobuf-java-format .

Here is the code

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);
 }
}

This fragment works as intended, but I doubt the string Object builder = method.invoke(new Object());, because when I call static methods, I always set it nullas the actual parameter.

In this case, I have a NullPointerException exception.

Does anyone have any idea why there is a need for an instance in the actual invoke () parameter?

Thanks Dario.

+5
source
1

javadoc , Method.invoke:
" invoke (Object obj, Object... args) "

:
" , obj . ."

, . , , .

0

All Articles