为什么A.class在运行时为空?

时间:2015-04-06 08:44:09

标签: java

我在程序中使用A.class时遇到问题,并在运行时返回java.lang.NullPointerException 这是我的剪辑代码:

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为空但我无法解释为什么会发生这种情况所以有人可以帮助我吗?

1 个答案:

答案 0 :(得分: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()是什么,但也许应该在某处分配{{1}}。