是否可以写null
to Parcel
当分割一个对象时,得到null
再次解压时又回来了?
假设我们有以下代码:
public class Test implements Parcelable {
private String string = null;
public Test(Parcel dest, int flags) {
source.writeString(string);
}
}
我会得到一个NullPointerException
当使用从包裹中读回该值时Parcel.readString()
?
或者我会得到一个null
值出来了?
是的,您可以通过null
to the Parcel.writeString(String)
method.
当你再次读出它时Parcel.readString()
,你会得到一个null
值出来。
例如,假设您有一个包含以下字段的类:
public class Test implements Parcelable {
public final int id;
private final String name;
public final String description;
...
您创建了Parcelable
像这样的实现(使用 Android Studio autoparcelable 工具):
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(null); // NOTE the null value here
dest.writeString(description);
}
protected Test(Parcel in) {
id = in.readInt();
name = in.readString();
description = in.readString();
}
运行此代码并传递Test
对象作为 Parcelable extra 中的一个Intent
,有 2 点变得显而易见:
-
代码运行完美没有任何
NullPointerException
- 反序列化的
Test
对象有一个值name == null
您可以在这个相关问题的评论中看到类似的信息:
- Parcel、ClassLoader 和读取 Null 值 https://stackoverflow.com/questions/26227095/parcel-classloader-and-reading-null-values
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)