Generic Class with Constraint access issue

前端 未结 2 925
耶瑟儿~
耶瑟儿~ 2021-02-14 22:51

This a general JAVA question. In android, there is an interface Parcelable:

This is an example inside the official documentation:

 public class MyParcela         


        
2条回答
  •  不知归路
    2021-02-14 23:26

    This doesn't answer your question as to how to access the static CREATOR property, however you do not need to access this property implement Parcelable. See below for example:

    public class TestModel implements Parcelable {
    
    private List items;
    private String someField;
    
    public List items() {
        return items;
    }
    
    public void setItems(List newValue) {
        items = newValue;
    }
    
    public String someField() {
        return someField;
    }
    
    public void setSomeField(String newValue) {
        someField = newValue;
    }
    
    //region: Parcelable implementation
    
    public TestModel(Parcel in) {
        someField = in.readString();
    
        int size = in.readInt();
        if (size == 0) {
            items = null;
        }
    
        else {
    
            Class type = (Class) in.readSerializable();
    
            items = new ArrayList<>(size);
            in.readList(items, type.getClassLoader());
        }
    }
    
    @Override
    public int describeContents() {
        return 0;
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(someField);
    
        if (items == null || items.size() == 0)
            dest.writeInt(0);
    
        else {
            dest.writeInt(items.size());
    
            final Class objectsType = items.get(0).getClass();
            dest.writeSerializable(objectsType);
    
            dest.writeList(items);
        }
    
        dest.writeInt(items.size());
        for(int i=0;i CREATOR = new Parcelable.Creator() {
        public TestModel createFromParcel(Parcel in) {
            return new TestModel(in);
        }
    
        public TestModel[] newArray(int size) {
            return new TestModel[size];
        }
    };
    
    //endregion
    }
    

提交回复
热议问题