問題描述
通過 Method.invoke() 調用靜態方法給了我 NPE (Static method invocation via Method.invoke() gave me NPE)
I'm dealing with Google Protobuf messages.
Since my needs are to set instance fields of an Object (some of them are Protobuff messages), I've wrote a function that retrieve via reflection the builder and through the protobuf‑java‑format recreates the message.
Here's 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 snippet works as intended, but my doubt is in the Object builder = method.invoke(new Object());
line since when I call static methods I've always put null
as actual parameter.
In this scenario I've a NullPointerException.
Have someone any idea why there is the need of a instance in the invoke() actual parameter?
Thanks Dario.
‑‑‑‑‑
參考解法
方法 1:
The javadoc for Method says the Method.invoke method signature is: "invoke(Object obj, Object... args)" It also says: "If the underlying method is static, then the specified obj argument is ignored. It may be null."
This means that your underlying method is NOT static. However you are checking to see if it is static it is not correct.
(by Dario、user1209809)