Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an inner class Parcelable

I need to know how to make an inner class Parcelable so that objects of its type can be passed via AIDL to a remote service. I cannot find any information on this.

Here is example code of what I am trying to accomplish, but it doesn't compile because the CREATOR in the Bar class cannot be static (ie because it's in an inner class). I cannot make Bar a static inner class and I cannot move Bar outside of the Foo class (other dependencies within the system). I also need to know how I would reference the Bar class from within an AIDL file. Any help is greatly appreciated.

public class Foo implements Parcelable
{
    private int a;

    public Foo()
    {
    }

    public Foo(Parcel source)
    {
        this.a = source.readInt();
    }

    public int describeContents()
    {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags)
    {
        dest.writeInt(this.a);
    }

    public static final Parcelable.Creator<Foo> CREATOR
    = new Parcelable.Creator<Foo>()
    {
        ...
    }

    public class Bar implements Parcelable
    {
        private int b;

        public Bar()
        {
        }

        public Bar(Parcel source)
        {
            this.b = source.readInt();
        }

        public int describeContents()
        {
            return 0;
        }

        public void writeToParcel(Parcel dest, int flags)
        {
            dest.writeInt(this.b);
        }

        public static final Parcelable.Creator<Bar> CREATOR
        = new Parcelable.Creator<Bar>()
        {
            ...
        }
    }
}
like image 214
MichaelL Avatar asked Jan 27 '12 00:01

MichaelL


1 Answers

I recently ran into the same problem and making the inner class static worked in my situation.

I read up on why this would actually work and it makes more sense to me, so I thought I would share. An inner class is a class that is nested inside another class and has a reference to an instantiation of its containing class. Through that reference it can access the containing classes members as if it were the containing class itself. Therefore it is bound to an instance of the containing class and thus can't have static members (since they would not be bound to the containing class).

Declaring the nested class as static decouples it from an instance of the containing class, and therefore can have its own static variables (and whatever else a regular class can have). Of course it will not be able to access members of the containing class.

like image 90
Aaron Avatar answered Oct 06 '22 02:10

Aaron