Android - 多态性和 Parcelable

dan*_*ela 5 java polymorphism android parcelable

从包裹中写入/读取时,我无法弄清楚如何使用多态性。我知道我需要在基类以及所有派生类中实现 Parcelable(在子类具有我想写入包裹的附加属性的情况下)。我不明白并且我不知道它是否可能是 - 如何从 Parcelable 读取子类,即,我怎么知道我正在从 Parcel 读取什么样的子类。我可以做一些 hack,比如在包中写入一些指示符,它会告诉我要使用什么类加载器,但我认为会有一些更优雅的方式,否则就没有太多的多态性使用。

为了说明我的问题,假设我有这样的课程:

形状类

public class Shape implements Parcelable {
public float area;

public Shape() {
}

public Shape(Parcel in) {
    area = in.readFloat();
}

public void writeToParcel(Parcel dest, int flags) {
    dest.writeFloat(area);
    }
//CREATOR etc..
}
Run Code Online (Sandbox Code Playgroud)

矩形形状类

 public class RectangleShape extends Shape {

    float a;
    float b;

    public RectangleShape(Parcel in) {
        super(in);
        a = in.readFloat();
        b = in.readFloat();
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeFloat(area);
        dest.writeFloat(a);
        dest.writeFloat(b);
    }

//CREATOR etc..
}
Run Code Online (Sandbox Code Playgroud)

圆形状类

public static class CircleShape extends Shape {
        float r;

    public CircleShape(Parcel in) {
        super(in);
        r = in.readFloat();
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeFloat(area);
        dest.writeFloat(r);
    }
//CREATOR etc..
 }
Run Code Online (Sandbox Code Playgroud)

现在,在其他一些课程中,我有这样的事情:

 public  class Geometry implements Parcelable {

    Shape myShape; 

    public Geometry (boolean condition) {

        if (condition) 
            myShape = new CircleShape(4.5);
        else
            myShape = new RectangleShape(3.4, 3.5);
    }


    @Override
    public Geometry(Parcel in) {
        in.readParcelable(??? - **how do I know what class loader to put here?** )
     }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeParcelable(myShape,flags);
    }
//CREATOR etc..
}
Run Code Online (Sandbox Code Playgroud)

有什么方法可以在写入包裹时“告诉”android它是什么子类,而不隐式检查实例类型?

et_*_*t_l 4

我编写了这个小片段并将其加载到FrameLayout主活动中进行检查 - 我得到了积极的结果(从包裹中重建的对象是类型,DerivedClass尽管对象的引用都是类型ObjectClass)。

import android.app.Fragment;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class Fragment2 extends Fragment {

    public ObjectClass obj;

    public static final String OBJECT_KEY = "Object key";

    public static Fragment2 newInstance(){
        Fragment2 fragment = new Fragment2();
        Bundle args = new Bundle();
        ObjectClass obj = new DerivedClass(); //a DerivedClass object
                               //referenced by an ObjectClass reference
        args.putParcelable(OBJECT_KEY, obj);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main2, container, false);
        if (savedInstanceState == null){
            Bundle args = getArguments();
            obj = args.getParcelable(OBJECT_KEY); //without supplying the ClassLoader
            ((TextView)view.findViewById(R.id.section_label)).setText(obj.getTitle()); 
                     //The text that is displayed is: "Child class"!
        }
        return view;
    }

    //The parent class
    public static class ObjectClass implements Parcelable {
        String title = "Parent class";

        public String getTitle(){
            return title;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {

        }

        public static final Creator<ObjectClass> CREATOR = new Creator<ObjectClass>() {
            @Override
            public ObjectClass createFromParcel(Parcel source) {
                return new ObjectClass();
            }

            @Override
            public ObjectClass[] newArray(int size) {
                return new ObjectClass[size];
            }
        };
    }

    //The child class
    public static class DerivedClass extends ObjectClass {
        String title2 = "Child class";

        public String getTitle() {
            return title2;
        }

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {

        }

        public static final Parcelable.Creator<DerivedClass> CREATOR = new Parcelable.Creator<DerivedClass>() {
            @Override
            public DerivedClass createFromParcel(Parcel source) {
                return new DerivedClass();
            }

            @Override
            public DerivedClass[] newArray(int size) {
                return new DerivedClass[size];
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

在主要活动中,在onCreate(Bundle)方法中:

getFragmentManager().beginTransaction().replace(R.id.frameContainer, Fragment2.newInstance()).commit();
Run Code Online (Sandbox Code Playgroud)

我的想法导致我进行此检查:由于 android 必须弄清楚在从包中重新创建对象时要使用哪个类(CREATOR要使用哪个类),我认为它必须将这些附加信息与指定信息(在方法中指定writeToParcel(Parcel, int))存储在一起将其放入捆绑包时。为了确定这个类,我认为它可以使用引用的类型或使用对象本身(例如getClass()在其上使用)。如果它使用对象类型本身,那当然意味着多态性是可能的。从我上面的检查来看,情况确实如此。

结论和对你的例子的猜测: 我认为对于你的例子,尽量不要显式地传递类加载器。经过null。从参数的文档中Parcel#readParcelable(ClassLoader)

ClassLoader:从中实例化 Parcelable 对象的 ClassLoader,或者默认类加载器为 null。

我没有尝试使用您的配置,因此我不确定它是否会以与我的示例中相同的方式工作。具体来说,我不确定是否Parcel#readParcelable(ClassLoader=null)实际上与Bundle#getParcelable(String). 但如果我的理由是正确的 - 它应该(我假设Bundle#getParcelable(String)只要Bundle#setClassLoader(ClassLoader)不被调用就使用默认的类加载器)。

请发表评论并告诉我它是否对您有用。