java 将对象成员写入包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9915347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing Objects members to Parcels
提问by tacos_tacos_tacos
So far I've been chugging along with Parcelable
objects without issue, mainly because all of their members have been types that have writeX()
methods associated with them. For example, I do:
到目前为止,我一直在使用Parcelable
对象而没有问题,主要是因为它们的所有成员都是具有writeX()
与其关联的方法的类型。例如,我这样做:
public String name;
private Foo(final Parcel in) {
name = in.readString(); }
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeString(name); }
But now if I have a Bar
member things get a little dicey for me:
但是现在如果我有Bar
会员,事情对我来说有点冒险:
public Bar bar;
private Foo(final Parcel in) {
bar = new Bar(); //or i could actually write some constructor for Bar, this is a demo.
bar.memberString = in.readString();
}
public void writeToParcel(final Parcel dest, final int flags) {
// What do I do here?
}
Am I approaching this the wrong way? What should I do in my writeToParcel
to parcel member Bar
s?
我是否以错误的方式接近这个?我应该在我writeToParcel
的包裹会员中做什么Bar
?
回答by yorkw
The correct and more OO way is make Bar implements Parcelable too.
正确且更面向对象的方法是让 Bar 也实现 Parcelable。
To read Bar in your private Foo constructor:
要在您的私有 Foo 构造函数中读取 Bar:
private Foo(final Parcel in) {
... ...
bar = in.readParcelable(getClass().getClassLoader());
... ...
}
To write Bar in your writeToParcel method:
要在 writeToParcel 方法中编写 Bar:
public void writeToParcel(final Parcel dest, final int flags) {
... ...
dest.writeParcelable(bar, flags);
... ...
}
Hope this helps.
希望这可以帮助。
回答by user123321
Parceables are a pain and only pass by value and not reference. I would never recommend using them. Make a static model instance if you application and just get a shim reference to the object you need.
Parceables 是一种痛苦,只能通过值传递而不是引用。我永远不会推荐使用它们。如果您应用程序并获得对所需对象的垫片引用,请制作一个静态模型实例。