在阅读JDK源代码时,我发现作者通常会检查参数是否为null,然后手动抛出新的NullPointerException().他们为什么这样做?我认为没有必要这样做,因为它会在调用任何方法时抛出新的NullPointerException().(这里是HashMap的一些源代码,例如:)
public V computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
if (remappingFunction == null)
throw new NullPointerException();
Node<K,V> e; V oldValue;
int hash = hash(key);
if ((e = getNode(hash, key)) != null &&
(oldValue = e.value) != null) {
V v = remappingFunction.apply(key, oldValue);
if (v != null) {
e.value = v;
afterNodeAccess(e);
return v;
}
else
removeNode(hash, key, null, false, true);
}
return null;
}
Run Code Online (Sandbox Code Playgroud) 为什么要使用Objects.requireNonNull()?
我注意到Oracle JDK中使用了许多Java 8方法,如果给定的对象(参数)是NullPointerException内部抛出null的NullPointerException.
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
Run Code Online (Sandbox Code Playgroud)
但是null如果NullPointerException对象被解除引用,则无论如何都会抛出.那么,为什么要进行额外的空检查和抛出
Objects.requireNonNull()?
一个明显的答案(或好处)是它使代码更具可读性,我同意.我很想知道Objects.requireNonNull()在方法开头使用的任何其他原因
.
我有一个代码:
public String getNameUpdateEvent(long id) {
Cursor mCursor =
db.rawQuery("select name from events WHERE _id=" + id + ";", null);
if (mCursor != null) {
mCursor.moveToFirst();
}
String updateNameEvent;
updateNameEvent = mCursor.getString(mCursor.getColumnIndex("name"));
return updateNameEvent;
}
Run Code Online (Sandbox Code Playgroud)
我收到了警告
Warning:(173, 45) Method invocation 'mCursor.getColumnIndex("name")' may produce 'java.lang.NullPointerException'
Run Code Online (Sandbox Code Playgroud)
我怎么能解决它?