2015-04-06 72 views
0

我在程序中使用的A.class時,它在運行時 返回顯示java.lang.NullPointerException遇到的問題這是我的文檔片斷代碼:爲什麼A.class在運行時爲空?

public synchronized boolean isDeviceEqual(IDevice dev) { 
    ............ 
    if(isDeviceInstanceOf(SimpleDevice.class)) { 
     return dev instanceof IDevice 
      && XXX(); 
    } 
    ............ 
} 
public boolean isDeviceInstanceOf(Class cls) { 
    return cls.isAssignableFrom(mDeviceClass); 
} 

和NPE

java.lang.NullPointerException 
at xxx/library/DeviceDescriptor.isDeviceInstanceOf(Ljava/lang/Class;)Z (:0:5) 
at xxx/library/DeviceDescriptor.isDeviceEqual(LIDevice;)Z (:0:6) 

以上NPE,這意味着在這種情況下cls爲空,但我無法解釋爲什麼會發生這種情況,因此任何人都可以幫助我?

回答

0

cls.isAssignableFrom(mDeviceClass)將拋出NullPointerException,如果mDeviceClass,這一定是這裏的情況,因爲您確定cls不爲空。

/** 
* Determines if the class or interface represented by this 
* <code>Class</code> object is either the same as, or is a superclass or 
* superinterface of, the class or interface represented by the specified 
* <code>Class</code> parameter. It returns <code>true</code> if so; 
* otherwise it returns <code>false</code>. If this <code>Class</code> 
* object represents a primitive type, this method returns 
* <code>true</code> if the specified <code>Class</code> parameter is 
* exactly this <code>Class</code> object; otherwise it returns 
* <code>false</code>. 
* 
* <p> Specifically, this method tests whether the type represented by the 
* specified <code>Class</code> parameter can be converted to the type 
* represented by this <code>Class</code> object via an identity conversion 
* or via a widening reference conversion. See <em>The Java Language 
* Specification</em>, sections 5.1.1 and 5.1.4 , for details. 
* 
* @param cls the <code>Class</code> object to be checked 
* @return the <code>boolean</code> value indicating whether objects of the 
* type <code>cls</code> can be assigned to objects of this class 
* @exception NullPointerException if the specified Class parameter is 
*   null. 
* @since JDK1.1 
*/ 
public native boolean isAssignableFrom(Class<?> cls); 

這似乎很奇怪,在isDeviceEqual(IDevice dev)你沒有做與dev什麼。我不知道mDeviceClass是什麼,但也許它應該在某處被分配dev.getClass()

+0

謝謝Eran,dev用於檢查IDevice的實例 – chinhspkt 2015-04-06 09:03:06

+0

謝謝Eran,dev用於檢查IDevice的實例,但它與isDeviceInstanceOf()無關。 NPE在程序運行時拋出,只發生一次。謝謝。 – chinhspkt 2015-04-06 09:08:54

相關問題