2013-02-18 75 views
5

我正在處理Google Protobuf消息。因爲我需要設置對象的實例字段(其中一些是Protobuff消息),所以我寫了一個函數,它通過構建器的反射來檢索,並通過protobuf-java-format重新創建消息。通過Method.invoke()的靜態方法調用給了我NPE

下面的代碼

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異常。

有任何人知道爲什麼有一個實例在調用()實際參數的需要?

謝謝達里奧。

+0

如果invoke引發NPE,則該方法不是靜態的。您可能想要檢查Modifier.isStatic(method.getModifiers()) – Javier 2013-02-18 10:09:34

+0

@Javier:我已經檢查了方法修飾符。控制給了我不幸的真實。 – Dario 2013-02-18 10:25:39

+0

我的主要疑慮是在protobuf部分。我沒有太多的經驗在這些生成的類... – Dario 2013-02-18 10:27:33

回答

0

的方法的Javadoc說Method.invoke方法簽名是:
「調用(obj對象,對象...參數)」
它還說:
「如果底層方法是靜態的,那麼指定的obj參數被忽略,它可能爲空。「

這意味着您的底層方法不是靜態的。但是,您正在檢查它是否是靜態的,它是不正確的。